简体   繁体   English

从 Pandas 多级 dataframe 制作 Plot 条

[英]Make a Plot Bar from Pandas multilevel dataframe

I'm having troubles trying to make a bar plot from a pandas dataframe, which should be easy but I can't make it work.我在尝试从 pandas dataframe 制作酒吧 plot 时遇到了麻烦,这应该很容易,但我无法让它工作。 I have a dataframe that looks like that:我有一个看起来像这样的 dataframe:

Data A数据A Data B资料 B Data C数据 C
timestamp时间戳
06:54:00 06:54:00 0.1 0.1 0.2 0.2 0.3 0.3

But instead of 3 columns with Data, I have 99. The point is that I am trying to do a bar plot representing in the x axis the different Data and in the y axis the values.但是,我有 99 列,而不是 3 列数据。关键是我正在尝试做一个条形 plot,在 x 轴上表示不同的数据,在 y 轴上表示值。

I tried with:我试过:

p = data.hvplot.bar(x = 'Data', y = 'Units', rot = 90)

And

p = data.plot(kind='bar', title="Data", figsize=(15, 10), legend=True, fontsize=12)

But none of them are working, and I think that the problem comes from the format of my dataframe, because of the column 'timestamp'.但是它们都不起作用,我认为问题出在我的 dataframe 的格式上,因为“时间戳”列。 However, I haven't manage to delete it, I tried:但是,我还没有设法删除它,我尝试了:

data = data.droplevel('timestamp')

And:和:

data = data.drop(['timestamp'], axis=1)

But none of them are working.但他们都没有工作。 Could someone please give me a hand with that?有人可以帮帮我吗?

Does this answer your question?这回答了你的问题了吗?

new_df = df.melt(var_name="Data")
new_df.plot(kind='bar', x='Data', y='value')

在此处输入图像描述

I finally managed to solve it.我终于设法解决了。

What I did was:我所做的是:

new_df = data.melt(var_name="Data")

To get a new dataframe without the timestamp.获取没有时间戳的新 dataframe。 Then:然后:

titles = new_df['Data'].to_list()

values = new_df['value'].to_list()

To get two lists, one with the titles and another one with the values.要获得两个列表,一个带有标题,另一个带有值。

And then I plotted the chart with the following code:然后我用以下代码绘制了图表:

        p = figure(x_range=titles, height=500, width=1500, title="Unit",
                   toolbar_location=None, tools="")

        p.vbar(x=titles, top=values, width=0.6)

        p.xgrid.grid_line_color = None
        p.xaxis.major_label_orientation = "vertical"
        p.y_range.start = 0

Thank you all,谢谢你们,

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM