Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pandas .plot() method won't take the specified colors in a bar diagram

I'm trying to graph how much each key in the keyboard is used, classifying by side of the keyboard.

For that I get a long string of text, I count the values for each letter and then make it into a pandas.DataFrame().

The DataFrame has this structure

    kp
e   12.534045
a   12.167107
o   9.238939
s   7.103866
n   6.470274

I'm plotting with

# Lazy definition of left_side and right_side of the keyboard
left_side  = [l for l in 'qwertasdfgzxcvb']
right_side = [l for l in 'yuiophjklñnm,.-'] 

# Plot the graph
df.plot(
    kind = 'bar',
    figsize = (10,5),
    color = ['r' if letter in left_side else 'b' for letter in df.index]
)

But this makes a plot with all red bars. I've checked and the generated list with list comprehension is actually how it should be (a list of 'r's and 'b's according to their location in the keyboard).

Any idea of what is going on here?

like image 241
Ruther Avatar asked Jan 25 '26 23:01

Ruther


1 Answers

I didn't find out where is wrong with color defined in df.plot(). But I find out a working one with plt.bar().

import pandas as pd
import matplotlib.pyplot as plt


data = {'kp': [12.534045, 12.167107, 9.238939, 7.103866, 6.470274]}
df = pd.DataFrame(data, columns=['kp'], index=['e','a','o','s','n'])

left_side  = [l for l in 'qwertasdfgzxcvb']
right_side = [l for l in 'yuiophjklñnm,.-'] 

color_list = ['r' if letter in left_side else 'b' for letter in df.index]

plt.bar(df.index, df['kp'], color=color_list)

plt.show()

enter image description here

like image 121
Ynjxsjmh Avatar answered Jan 28 '26 13:01

Ynjxsjmh