How to plot bar chart when the columns of the data are each day of each month?

老子叫甜甜 提交于 2019-12-13 22:52:21

问题


I don't know how to plot the bar chart like this photo.

Can anyone help me please?


回答1:


The pandas command Series.plot.bar accepts a color keyword, where you can input a list of colors (in RGBA or color names). I'm not entirely sure on what logic does the command follow when the list is too short, but if the list is the right length, it'll work. Example:

%matplotlib inline
import pandas as pd
this_series = pd.Series([0.5, 0.6, 0.1, 0.1, 0.05, 0.05, 0.7, 0.3, 0.2], name='foo')
this_series.plot.bar(color=['blue','black', 'brown', 'red','red','green','yellow'])

EDITED:

from your comments, I think I can understand your question. In the future, please help the community help you by crafting clearer questions.

To plot the sum of values per month, with your data structure being as in the example, you can do like this:

data (see - a minimal example that is still enough to work with):

df = pd.DataFrame(columns = ['hour_formatted', '11_jan_18', '13_jan_18', '14_mar_18'],
                 data = [['00:00', 3, 3, 4], ['00:01', 6, 3, 4], ['00:01', 100, 300, 500]])

The "hour" is unneeded, and we can sum the data values per day (after all, we'll sum them by month... or so I think).

df2 = df.drop('hour_formatted', axis=1).sum()

Afterwards, we only need the month from the day. In your format, it's the second item when splitting by '_':

df2.index = [x.split('_')[1] for x in df2.index]
df2.index.rename('month', inplace=True)

Afterwards, you can group by month (see groupby from docs), and plot a bar plot:

df3 = df2.reset_index().groupby('month').sum()[0] # the [0] part is to take first column from a dataframe that's created here. There might be a more elegant way
df3.plot.bar(color=['black', 'red'])


来源:https://stackoverflow.com/questions/57584172/how-to-plot-bar-chart-when-the-columns-of-the-data-are-each-day-of-each-month

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!