![](/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.