python - 如何绘制混合条形图和折线图并获取 x 轴作为年份

标签 python pandas matplotlib

我是 Python 新手,目前正在尝试使用条形图和线条绘制数据框中的数据。

[环境]

OS: Windows 7 - 64bit
Visual Studio Code 1.45.1
Python 2020.6.91350

以下是csv格式的基础数据,通过下面的代码读取。

[测试数据.csv]

year,ordered,sold,YoY-ordered,YoY-sold
2015,100,80,0.1,-0.05
2016,120,100,0.2,0.25
2017,100,130,-0.166666667,0.3
2018,80,90,-0.2,-0.307692308
2019,90,95,0.125,0.055555556
2020,100,90,0.111111111,-0.052631579

[代码.py]

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

df = pd.read_csv('./testData.csv')
df=df.set_index("year")

idxO = "ordered"
idxS = "sold"
idxOYoY = "YoY-ordered" 
idxSYoY = "YoY-sold"

fig = plt.figure(figsize=(12,5))
fig.suptitle("title")
ax1 = fig.add_subplot()
ax2 = ax1.twinx()
ax1.set_ylabel("Ordered, Sold")
ax2.set_ylabel("YoY")

df[[idxO, idxS]].plot(ax=ax1,kind="bar", color=["black","gray"])
df[[idxOYoY, idxSYoY]].plot(ax=ax2,kind="line", marker="o", color=["blue","lightblue"])

handler1, label1 = ax1.get_legend_handles_labels()
handler2, label2 = ax2.get_legend_handles_labels()
ax1.legend(handler1 + handler2, label1 + label2)
ax2.get_legend().remove()
plt.show()

它给出了下面的图表。

result1

我发现如果我不将年份设置为数据框的索引(注释掉df=df.set_index("year"),我可以得到我想要的图表,除了x轴的值之外)

result2

我想要做的是使用 x 轴的正确索引(年份)创建绘图。

最佳答案

  • 使用 pandas.DataFrame.plot 可以轻松创建这种类型的图。和 .twinx()
    • 如下面的代码所示,所有的标签信息都可以在图中设置
    • matplotlib.axes.Axes 返回,因此将绘图分配给 ax ,然后创建ax2 .
  • 'year'下面代码中没有设置为索引
import pandas as pd
import matplotlib.pyplot as plt

# test data
data = {'year': [2015, 2016, 2017, 2018, 2019, 2020], 'ordered': [100, 120, 100, 80, 90, 100], 'sold': [80, 100, 130, 90, 95, 90], 'YoY-ordered': [0.1, 0.2, -0.166666667, -0.2, 0.125, 0.111111111], 'YoY-sold': [-0.05, 0.25, 0.3, -0.307692308, 0.055555556, -0.052631579]}
df = pd.DataFrame(data)

# display(df)
   year  ordered  sold  YoY-ordered  YoY-sold
0  2015      100    80     0.100000 -0.050000
1  2016      120   100     0.200000  0.250000
2  2017      100   130    -0.166667  0.300000
3  2018       80    90    -0.200000 -0.307692
4  2019       90    95     0.125000  0.055556
5  2020      100    90     0.111111 -0.052632

# plot the bars with a pandas.DataFrame.plot and assign the plot to ax
ax = df.plot.bar(x='year', y=['ordered', 'sold'], ylabel='Ordered / Sold', xlabel='Year', color=['black', 'gray'], figsize=(12, 5))

# create ax2
ax2 = ax.twinx()

# plot the lines
df.plot(x='year', y=['YoY-ordered', 'YoY-sold'], marker='o', ylabel='YoY', color=['blue', 'lightblue'], ax=ax2)

# locate the legend
ax.legend(loc="upper left")
ax2.legend(loc='upper right')

plt.show()

enter image description here

来自OP的代码

  • 顺便说一下,我也运行了你的代码,'year'作为数据帧索引,并且绘制没有问题。
  • 所有代码均在 JupyterLab、Spyder、裸 Python 解释器和 PyCharm Pro 2020.3.2 中进行了测试,pandas 1.2.0matplotlib 3.3.2 .
  • 我使用Anaconda distribution ,我推荐,我每周更新 conda update --all ,否则您需要使用 pip 进行更新

enter image description here

关于python - 如何绘制混合条形图和折线图并获取 x 轴作为年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65696700/

相关文章:

python - pypi 包的 apt 依赖项

python - 返回带字符的字符串 - 其中数字彼此跟随

pandas - 如果另一列的值以特定字符串结尾,则更改列值

Python 2.7 : Pandas datetime does not work for future dates?

python - 如何将系列与数据框合并并保留双方数据

python - 更改已创建的 matplotlib 图形上的字体和线条粗细

python - python中相同类别的固定颜色条形图

python - Matplotlib 复选框(上一个和下一个)

python - py.test 运行成功后,模块 'threading' 中的 KeyError

python - 我自己的方法用于 list_display 和值作为 bool 图标