![](/img/trans.png)
[英]Pandas Matplotlib: How to change shape and size of the legend in scatter plot?
[英]Matplotlib plot size/legend issue
我正在尝试将图例放置在 matplotlib 图下方的空间中。 我使用唯一标识符创建每个子图,然后使用 plt.figure() 调整图的大小。 当我指定绘图大小时,绘图周围的空间消失(PNG 收紧了绘图周围的布局)。 这是我的代码:
fig = plt.subplot(111)
plt.figure(111,figsize=(3,3))
plots = []
legend = []
#fig.set_xlim([0, 20])
#fig.set_ylim([0, 1])
#ticks = list(range(len(k_array)))
#plt.xticks(ticks, k_array)
plt.plot(k_array, avgNDCG, 'red')
legend.append("eco overall F1")
if data_loader.GSQb:
legend.append("GSQ F1")
plt.plot(k_array, avgGSQNDCG, 'orange')
if data_loader.BSQb:
legend.append("BSQ F1")
plt.plot(k_array, avgBSQNDCG, 'purple')
if data_loader.GWQb:
legend.append("GWQ F1")
plt.plot(k_array, avgGWQNDCG, 'black')
if data_loader.BWQb:
legend.append("BWQ F1")
plt.plot(k_array, avgBWQNDCG, 'green')
if data_loader.GAQb:
legend.append("GAQ F1")
plt.plot(k_array, avgGAQNDCG, 'blue')
fig.legend(legend, loc='center', bbox_to_anchor=(0, 0, .7, -2),fontsize='xx-small')
plt.savefig("RARE " + metaCat + " best avg NDCG scores")
当我注释掉plt.figure(111,figsize=(3,3))
,图下方和周围的空白区域是可见的:
但是当我取消注释时:
请帮助我了解如何修改绘图大小、图例和布局间距,使其看起来更像1,但绘图更大。
如果您为绘图函数添加标签,那么您将不必提供带有句柄和标签的 legend() - 这更方便。
我建议使用循环结构而不是多个 if 语句。
关于图例,使用 ncol 参数将在这里为您提供很多帮助。 您可能会发现 matplotlib 文档图例教程很有帮助
如果您正在处理具有不同大小的多个子图,那么我建议使用gridspec ,否则只需使用带有 ncols 和 nrows 参数的plt.subplots() 。 例如:
图,轴 = plt.subplots(ncols=2, nrows=5, figsize=(12,12))
axis = axes.flatten() #这会产生一个包含 10 个轴的一维数组
我模拟了您的数据并实现了我认为您在下面寻找的内容。
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
#simulate data
df = pd.DataFrame({'x' : [1, 2, 3]})
for i in range(11):
df['Line_' + str(i)] = np.random.random_sample(3)
fig, ax = plt.subplots(figsize=(12,2.5))
# Change x and y values for troubleshooting purposes
ax.plot(df.x, df.Line_1, 'red', label='eco overall F1')
# This would be a good place to implement a for loop
# Change all conditions to true for troubleshooting purposes
if True:
ax.plot(df.x, df.Line_1, 'orange', label='GSQ F1')
if True:
ax.plot(df.x, df.Line_2, 'purple', label='BSQ F1')
if True:
ax.plot(df.x, df.Line_3, 'black', label='GWQ F1')
if True:
ax.plot(df.x, df.Line_4, 'green', label='BWQ F1')
if True:
ax.plot(df.x, df.Line_5, 'blue', label='GAQ F1')
legend = ax.legend(ncol=4, bbox_to_anchor=(0.5,-0.5), loc='lower center', edgecolor='w')
hide_spines = [ax.spines[x].set_visible(False) for x in ['top','right']]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.