python - 在 Matplotlib 中使用 Hlines 破坏传说

标签 python matplotlib bar-chart data-science data-analysis

在图表中的 100 级添加 axline/hline 后,我正在努力调整我的情节图例。(已添加屏幕截图)

如果有一种方法可以正确运行它,那么图例中不会丢失任何信息,并且可以添加另一个 hline 并将其添加到图例中。

在这里添加代码,可能是我写的不对。

fig, ax1 = plt.subplots(figsize = (9,6),sharex=True)

BundleFc_Outcome['Spend'].plot(kind = 'bar',color = 'blue',width = 0.4, ax = ax1,position = 1)
#
# Make the y-axis label, ticks and tick labels match the line color.
ax1.set_ylabel('SPEND', color='b', size = 18)
ax1.set_xlabel('Bundle FC',color='w',size = 18)

ax2 = ax1.twinx()
ax2.set_ylabel('ROAS', color='r',size = 18)
ax1.tick_params(axis='x', colors='w',size = 20)
ax2.tick_params(axis = 'y', colors='w',size = 20)
ax1.tick_params(axis = 'y', colors='w',size = 20)
#ax1.text()
#

ax2.axhline(100)
BundleFc_Outcome['ROAS'].plot(kind = 'bar',color = 'red',width = 0.4, ax = ax2,position = 0.25)
plt.grid()
#ax2.set_ylim(0, 4000)
ax2.set_ylim(0,300)
plt.title('ROAS & SPEND By Bundle FC',color = 'w',size= 20)
plt.legend([ax2,ax1],labels = ['SPEND','ROAS'],loc = 0)

代码给了我下面的图片:

result of above code

执行评论中的建议后,图片是这样的(没有解决问题):

result after changing legend location

最佳答案

您可以使用 bbox_to_anchor 属性手动设置图例位置。

ax1.legend([ax1],labels = ['SPEND'],loc='upper right', bbox_to_anchor=(1.25,0.70))
plt.legend([ax2,ax1],labels = ['SPEND','ROAS'],loc='upper right', bbox_to_anchor=(1.25,0.70))

https://matplotlib.org/users/legend_guide.html#legend-location

关于python - 在 Matplotlib 中使用 Hlines 破坏传说,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54646913/

相关文章:

python - Matplotlib - 如何为具有对数刻度的线图设置颜色条

python - 使用 matplotlib 在 x 轴上绘制 datetimeindex 在 pandas 0.15 和 0.14 中创建错误的刻度

python - 如何在保持分辨率的同时将 2D float numpy 数组无损保存到灰度图像中?

python - 如何手动将包安装到 anaconda 的 python 发行版中?

python - 寻找包含值的边界?

excel - 更改条形图中的条形颜色

java - 自定义 java BarChart 缩放问题

python - 属性错误: 'NoneType' object has no attribute 'dtype'

python - matplotlib 中的阶跃函数

r - 在 ggplot2 中结合 position_dodge 和 position_fill