gpt4 book ai didi

python - 具有线条和区域样式的 Matplotlib 图例

转载 作者:太空宇宙 更新时间:2023-11-04 03:11:45 26 4
gpt4 key购买 nike

我正在尝试在同一个图中绘制线图和面积图,并使用同时显示线型和面积型的图例。不幸的是,下面的代码在图例中只产生线条而没有区域。

是否可以在同一个图例中同时获得线条和区域?如果没有,我可以在同一张图上得到面积图的第二个图例吗?

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

dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(np.abs(np.random.randn(6,4)), index=dates, columns=list('ABCD'))
f, ax = plt.subplots()
df[['A','B']].plot(ax=ax, figsize=(10,5))
df[['C','D']].plot(kind='area',ax=ax, figsize=(10,5))
ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

plot of line and area graphs

最佳答案

您可以通过以下方式进行:

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

# data
dates = pd.date_range('20130101', periods=6)
df = pd.DataFrame(np.abs(np.random.randn(6,4)),
index=dates,
columns=list('ABCD'))

# plot
f, ax = plt.subplots()
# lines A and B
lineA, = ax.plot(df.index, df['A'], color = 'black', label = 'A')
lineB, = ax.plot(df.index, df['B'], color = 'green', label = 'B')
# stacked plots
ax.fill_between(df.index, 0, df['C'], color = 'blue',label = 'C')
ax.fill_between(df.index, df['C'], df['D'], color = 'red', label = 'D')
# Labels for both stacked plots
blue_patch = patches.Patch(color='blue', label='C')
red_patch = patches.Patch(color='red', label='D')
# legend
ax.legend(handles = [lineA, lineB, blue_patch, red_patch],
loc='center left', bbox_to_anchor=(1, 0.5))
# show the final plot
f.show()

查看 legend guide here .

关于python - 具有线条和区域样式的 Matplotlib 图例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37792305/

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