【问题标题】:Plotting a bar chart comparing years in pandas绘制比较熊猫年份的条形图
【发布时间】:2018-05-16 03:25:05
【问题描述】:

我有以下数据框

Date_x  BNF Chapter_x   VTM_NM  Occurance_x     Date_y  BNF Chapter_y   Occurance_y
0   2016-12-01  1   Not Specified   2994      2015-12-01    1           3212
1   2016-12-01  1   Mesalazine      2543      2015-12-01    1           2397
2   2016-12-01  1   Omeprazole      2307      2015-12-01    1           2370
3   2016-12-01  1   Esomeprazole    1535      2015-12-01    1           1516
4   2016-12-01  1   Lansoprazole    1511      2015-12-01    1           1547

我使用此代码绘制了一个带有 2 个条形图的条形图,一个代表 2015 年,另一个代表 2016 年

fig = plt.figure() # Create matplotlib figure
ax = fig.add_subplot(111) # Create matplotlib axes
width = 0.4

df.Occurance_x.plot(kind='bar', color='red', ax=ax, width=width, position=1)
df.Occurance_y.plot(kind='bar', color='blue', ax=ax, width=width, position=0)

ax.set_ylabel('Occurance')
plt.legend(['Date_x', 'Date_y'], loc='upper right')
ax.set_title('BNF Chapter 1 Top 5 drugs prescribed')


plt.show()

但是 x 轴显示索引 0 1 2 3 4

- I want it to show the drug names

我该怎么做呢?

【问题讨论】:

  • 您能展示一下您尝试过的内容吗?
  • @Abhijeetk431 我已经编辑了我的帖子以显示我如何绘制一个条形图,但我不确定如何合并它们以创建 2 个图表
  • 您为什么不:-将年份添加到您的数据框中-合并药物名称上的 2 个数据框与此 df 一起使用。我不清楚您如何以及为什么想要 y 轴的非数值。
  • @user32185 我曾尝试使用 concat 连接两个数据帧,但它不起作用,它将数据帧拉到下面而不是 2015 年的 16。你知道我可以这样做吗?跨度>
  • @user32185 我已经成功合并了 2 个数据框,但我不确定现在如何在条形图上绘制它,条形图显示 2015 年和其他 2016 年

标签: python python-3.x pandas matplotlib jupyter-notebook


【解决方案1】:

我猜你可以从这里开始玩了。

import pandas as pd
df = pd.DataFrame({"date_x":[2015]*5,
                   "Occurance_x":[2994, 2543, 2307, 1535, 1511],
                   "VTM_NM":["Not Specified", "Mesalazine", "Omeprazole",
                             "Esomeprazole", "Lansoprazole"],
                   "date_y":[2016]*5,
                   "Occurance_y":[3212, 2397, 2370, 1516, 1547]})

ax = df[["VTM_NM","Occurance_x", "Occurance_y"]].plot(x='VTM_NM', 
                                                      kind='bar', 
                                                      color=["g","b"],
                                                      rot=45)
ax.legend(["2015", "2016"]);

【讨论】:

    猜你喜欢
    • 2021-06-16
    • 1970-01-01
    • 1970-01-01
    • 2021-01-11
    • 2016-09-27
    • 2021-06-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多