Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/283.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 在Matplotlib中使用hline会破坏图例_Python_Matplotlib_Bar Chart_Data Science_Data Analysis - Fatal编程技术网

Python 在Matplotlib中使用hline会破坏图例

Python 在Matplotlib中使用hline会破坏图例,python,matplotlib,bar-chart,data-science,data-analysis,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 =

在图中添加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)
代码给出了以下图片:

实施评论中的建议后,图片如下(无法解决问题):


您可以使用bbox\u to\u 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))

因此,由于某种原因,最终找到了更简单的解决方法 甚至设法在最低支出的2级增加了另一个阈值。


我不建议使用pandas的内置函数来进行更复杂的绘图。此外,在提问时,通常礼貌地提供最少且可验证的示例(请参阅)。我冒昧地模拟了你的问题

由于轴的变化,我们需要生成自己的图例。首先是结果:

可通过以下方式实现:

import matplotlib.pyplot as plt, pandas as pd, numpy as np
# generate dummy data.
X  = np.random.rand(10, 2)
X[:,1] *= 1000
x  = np.arange(X.shape[0]) * 2 # xticks
df = pd.DataFrame(X, columns = 'Spend Roast'.split())
# end dummy data

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

# tmp axes
axes = [ax1, ax2] # setup axes
colors = plt.cm.tab20(x)
width = .5 # bar width

# generate dummy legend
elements = []
# plot data
for idx, col in enumerate(df.columns):
    tax = axes[idx]
    tax.bar(x + idx * width, df[col], label = col, width = width, color = colors[idx])
    element = tax.Line2D([0], [0], color = colors[idx], label = col) # setup dummy label
    elements.append(element)
# desired hline
tax.axhline(200, color = 'red')
tax.set(xlabel = 'Bundle FC', ylabel = 'ROAST')
axes[0].set_ylabel('SPEND')
tax.legend(handles = elements)

使用
bbox\u to\u锚定
属性将图例移动到一侧
plt.legend([ax2,ax1],labels=['SPEND','ROAS',loc='右上角',bbox_to_anchor=(1.25,0.80))
不幸的是,这并没有保持“SPEND”legend颜色(蓝色矩形)不变,添加了没有ncol属性的打印屏幕尝试
plt.legend([ax2,ax1],labels=['SPEND','ROAS',loc='右上角',bbox_to_anchor=(1.25,0.80))
或将bbox_移至_anchor因为我们没有您的数据,很遗憾,我们无法运行您的代码来验证问题。您是否可以尝试添加第三个标签,在您的
plt.legend
通话中说“test”,看看会发生什么?@NihalSangeeth问题不在于legend的位置,而在于'SPEND'的蓝色补丁被替换为
hline
通话中的一行。在我自己的plt.title上解决了它('ROAS&SPEND By Region',color='w',size=20)fig.legend([ax2,ax1],labels=['SPEND','ROAS',loc=0)plt.hlines([100,20],xmin=0,xmax=8,color=['r','b'])更好的解决方案+1请查看我的解决方案,以防您需要它为您的体形添加更复杂的内容。它提供了一种更通用(以matplotlib为中心)的方法。
import matplotlib.pyplot as plt, pandas as pd, numpy as np
# generate dummy data.
X  = np.random.rand(10, 2)
X[:,1] *= 1000
x  = np.arange(X.shape[0]) * 2 # xticks
df = pd.DataFrame(X, columns = 'Spend Roast'.split())
# end dummy data

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

# tmp axes
axes = [ax1, ax2] # setup axes
colors = plt.cm.tab20(x)
width = .5 # bar width

# generate dummy legend
elements = []
# plot data
for idx, col in enumerate(df.columns):
    tax = axes[idx]
    tax.bar(x + idx * width, df[col], label = col, width = width, color = colors[idx])
    element = tax.Line2D([0], [0], color = colors[idx], label = col) # setup dummy label
    elements.append(element)
# desired hline
tax.axhline(200, color = 'red')
tax.set(xlabel = 'Bundle FC', ylabel = 'ROAST')
axes[0].set_ylabel('SPEND')
tax.legend(handles = elements)