Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
638 views
in Technique[技术] by (71.8m points)

python - Pandas DataFrame Bar Plot - Plot Bars Different Colors From Specific Colormap

How do you plot the bars of a bar plot different colors only using the pandas dataframe plot method?

If I have this DataFrame:

df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index()

   index  count
0      0   3372
1      1  68855
2      2  17948
3      3    708
4      4   9117

What df.plot() arguments do I need to set so each bar in the plot:

  1. Uses the 'Paired' colormap
  2. Plots each bar a different color

What I am attempting:

df.plot(x='index', y='count', kind='bar', label='index', colormap='Paired', use_index=False)

The result:

not different colors

What I already know (yes, this works, but again, my purpose is to figure out how to do this with df.plot ONLY. Surely it must be possible?):

def f(df):
  groups = df.groupby('index')

  for name,group in groups:
    plt.bar(name, group['count'], label=name, align='center')

  plt.legend()
  plt.show()

end result but used for loop

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no argument you can pass to df.plot that colorizes the bars differently for a single column.
Since bars for different columns are colorized differently, an option is to transpose the dataframe before plotting,

ax = df.T.plot(kind='bar', label='index', colormap='Paired')

This would now draw the data as part of a subgroup. Therefore some tweaking needs to be applied to set the limits and xlabels correctly.

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index()

ax = df.T.plot(kind='bar', label='index', colormap='Paired')
ax.set_xlim(0.5, 1.5)
ax.set_xticks([0.8,0.9,1,1.1,1.2])
ax.set_xticklabels(range(len(df)))
plt.show()

enter image description here

While I guess this solution matches the criteria from the question, there is actually nothing wrong with using plt.bar. A single call to plt.bar is sufficient

plt.bar(range(len(df)), df["count"], color=plt.cm.Paired(np.arange(len(df))))

enter image description here

Complete code:

import matplotlib.pyplot as plt
import pandas as pd
import numpy as np

df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index()

plt.bar(range(len(df)), df["count"], color=plt.cm.Paired(np.arange(len(df))))

plt.show()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...