如何在条形图上正确绘制一条线?

时间:2021-02-07 00:49:47

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

这个曾经工作得很好,但不知何故它停止工作(我一定是错误地更改了一些东西,但我找不到问题)。

我正在绘制每个日期的一组 3 个条形图,以及一条显示其中一个的累积值的线。但只有一个或另一个(条形或线条)被正确绘制。如果我最后留下条形的代码,则只绘制条形。如果我最后留下该行的代码,则只绘制该行。

fig, ax = plt.subplots(figsize = (15,8))

df.groupby("date")["result"].sum().cumsum().plot(
    ax=ax,
    marker='D',
    lw=2,
    color="purple")

df.groupby("date")[selected_columns].sum().plot(
    ax=ax,
    kind="bar",
    color=["blue", "red", "gold"])

ax.legend(["LINE",  "X", "Y", "Z"])

感谢您的帮助!

enter image description here

enter image description here

2 个答案:

答案 0 :(得分:1)

Pandas 以 x 轴为分类绘制条形图,因此内部编号为 0, 1, 2, ...,然后设置标签。线图使用日期作为 x 轴。要将它们结合起来,两者都需要分类。最简单的方法是从线图中删除索引。确保先绘制线图,以便条形图正确设置标签。

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

df = pd.DataFrame({'date': pd.date_range('20210101', periods=10),
                   'earnings': np.random.randint(100, 600, 10),
                   'costs': np.random.randint(0, 200, 10)})
df['result'] = df['earnings'] - df['costs']

fig, ax = plt.subplots(figsize=(15, 8))

df.groupby("date")["result"].sum().cumsum().reset_index(drop=True).plot(
    ax=ax,
    marker='D',
    lw=2,
    color="purple")
df.groupby("date")[['earnings', 'costs', 'result']].sum().plot(
    ax=ax,
    kind="bar",
    rot=0,
    width=0.8,
    color=["blue", "red", "gold"])
ax.legend(['Cumul.result', 'earnings', 'costs', 'result'])
# shorten the tick labels to only the date
ax.set_xticklabels([tick.get_text()[:10] for tick in ax.get_xticklabels()])
ax.set_ylim(ymin=0) # bar plots are nicer when bars start at zero
plt.tight_layout()
plt.show()

example plot

答案 1 :(得分:0)

我在这里发布解决方案:

import matplotlib.pyplot as plt
import matplotlib.ticker as mtick
a=[11.3,222,22, 63.8,9]  
b=[0.12,-1.0,1.82,16.67,6.67]
l=[i for i in range(5)]

plt.rcParams['font.sans-serif']=['SimHei'] 
fmt='%.1f%%'
yticks = mtick.FormatStrFormatter(fmt)

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(l, b,'og-',label=u'A')
ax1.yaxis.set_major_formatter(yticks)
for i,(_x,_y) in enumerate(zip(l,b)):
    plt.text(_x,_y,b[i],color='black',fontsize=8,)
ax1.legend(loc=1)
ax1.set_ylim([-20, 30])
ax1.set_ylabel('ylabel')
plt.legend(prop={'family':'SimHei','size':8})
ax2 = ax1.twinx() 
plt.bar(l,a,alpha=0.1,color='blue',label=u'label')
ax2.legend(loc=2)
plt.legend(prop={'family':'SimHei','size':8},loc="upper left")
plt.show()

enter image description here

这个的关键是命令

ax2 = ax1.twinx() 
相关问题