简体   繁体   English

根据数据框制作2个变量的条形图

[英]Make a bar graph of 2 variables based on a dataframe

I am trying to plot a graph of two variables but without success. 我试图绘制两个变量的图,但没有成功。 My goal is to to create a bar graph where the Events1 And Events2 appear along in order to be easier to compare the "Name" (two bars for each Name). 我的目标是创建一个在其中出现Event1和Events2的条形图,以便于比较“名称”(每个名称两个条形)。 My code below generates two graphs wrongly. 我下面的代码错误地生成了两个图形。 Can you point me out to the correct way of doing this?Thanks. 您能指出我正确的做法吗?谢谢。

My df is: 我的df是:

         Name  Events1 Events2
0  Accounting        3       3
1   Reporting        1       4
2     Finance        1      13
3       Audit        1      17
4    Template        2      40

Code: 码:

import matplotlib.pyplot as plt
ax = df[['Events1','Events2']].plot(kind='bar', title ="test", figsize=(15, 10), legend=True, fontsize=12)
ax.set_xlabel("Name", fontsize=12)
ax.set_ylabel("Number", fontsize=12)
plt.show()

Use set_index 使用set_index

In [3596]: df.set_index('Name').plot.bar()
Out[3596]: <matplotlib.axes._subplots.AxesSubplot at 0x2954d208>

在此处输入图片说明


In [3595]: df.set_index('Name')
Out[3595]:
            Events1  Events2
Name
Accounting        3        3
Reporting         1        4
Finance           1       13
Audit             1       17
Template          2       40

You can simply pass two Y-axis values 您可以简单地传递两个Y轴值

df.plot.bar(x = 'Name', y = ['Events1', 'Events2'], rot = 40)

If you wish to annotate the bars, try 如果您想注释条,请尝试

fig, ax = plt.subplots()
df.plot.bar(x = 'Name', y = ['Events1', 'Events2'], rot = 40, ax = ax)
for p in ax.patches: 
    ax.annotate(np.round(p.get_height(),decimals=2), (p.get_x()+p.get_width()/2., p.get_height()))

在此处输入图片说明

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

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