gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 08:16:07 25 4
gpt4 key购买 nike

我是 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
我发现我可以得到我想要的图表,除了 x 轴的值,如果我没有将年份设置为数据框的索引(注释掉 df=df.set_index("year"))
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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com