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

Viewed 309

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?

2 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

colors refers to the colors of columns (you have only one column so only first 'r' is used), one solution is to seperate into two pandas columns, plot a stacked bar to get things in the right place:

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

df['kpl'] = [x[1] if x[0] in (left_side) else None for x in zip(df.index, df.kp)]
df['kpr'] = [x[1] if x[0] in (right_side) else None for x in zip(df.index, df.kp)]

# Plot the graph
df[['kpl', 'kpr']].plot(
    kind = 'bar',
    figsize = (10,5),
    color = ['r', 'b'],
    stacked=True
)

enter image description here

Related