我有一個圖,其中包含我用熊貓資料框中的資料創建的子圖:
# Definition of the dataframe
df = pd.DataFrame({'Colors': {0: 'Red', 1: 'Blue', 2: 'Green', 3: 'Blue', 4: 'Red'}, 'X_values': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}, 'Y_values': {0: 2, 1: 4, 2: 8, 3: 10, 4: 4}, 'MinY_values': {0: 1.5, 1: 3, 2: 7.5, 3: 8, 4: 2}, 'MaxY_values': {0: 2.5, 1: 5, 2: 9.5, 3: 11, 4: 6}})
我定義了兩個串列,其中包含圖中每個點的顏色以及我想分配給每個點的標簽(然后,如果需要,我可以更改給定點的標簽):
color
Out[8]: ['red', 'blue', 'green', 'blue', 'red']
labels
Out[9]:
['It is a red point',
'What a wonderful blue point',
'Sounds to be a green point',
'What a wonderful blue point',
'It is a red point']
在每個子圖上,我需要添加一條水平線。
這是我的問題:當我向圖形添加圖例時,如果顏色重復,則標簽會重復,并且水平線包含在圖例中,這將“移動”圖例。
如何忽略圖例中重復的顏色以及不包括黑線?

這是我的代碼:
import pandas as pd
from matplotlib.pyplot import show, subplots
# Definition of the dataframe
df = pd.DataFrame({'Colors': {0: 'Red', 1: 'Blue', 2: 'Green', 3: 'Blue', 4: 'Red'}, 'X_values': {0: 1, 1: 2, 2: 3, 3: 4, 4: 5}, 'Y_values': {0: 2, 1: 4, 2: 8, 3: 10, 4: 4}, 'MinY_values': {0: 1.5, 1: 3, 2: 7.5, 3: 8, 4: 2}, 'MaxY_values': {0: 2.5, 1: 5, 2: 9.5, 3: 11, 4: 6}})
# Definition of the different colors and labels
color = []
labels = []
for i in df['Colors']:
if i == 'Red':
color.append('red')
labels.append('It is a red point')
if i == 'Blue':
color.append('blue')
labels.append('What a wonderful blue point')
if i == 'Green':
color.append('green')
labels.append('Sounds to be a green point')
# Figure
fig,axes = subplots(3,1,sharex = True)
fig.subplots_adjust(top=0.975,
bottom=0.07,
left=0.05,
right=0.585,
hspace=0.0,
wspace=0.2)
for x_val,y_val,min_val,max_val,colors in zip(df['X_values'],df['Y_values'],df['MinY_values'],df['MaxY_values'],color):
axes[0].errorbar(x_val,y_val,yerr = [[min_val],[max_val]] ,color = colors,barsabove='True',fmt = 'o')
axes[0].axhline(y=5, color='black', linestyle='--')
for x_val,y_val,min_val,max_val,colors in zip(df['X_values'],df['Y_values'],df['MinY_values'],df['MaxY_values'],color):
axes[1].errorbar(x_val,y_val,yerr = [[min_val],[max_val]] ,color = colors,barsabove='True',fmt = 'o')
axes[1].axhline(y=5, color='black', linestyle='--')
for x_val,y_val,min_val,max_val,colors in zip(df['X_values'],df['Y_values'],df['MinY_values'],df['MaxY_values'],color):
axes[2].errorbar(x_val,y_val,yerr = [[min_val],[max_val]] ,color = colors,barsabove='True',fmt = 'o',label = labels)
axes[2].axhline(y=5, color='black', linestyle='--')
# Legend
fig.legend(labels)
fig.legend(bbox_to_anchor=(2,2), loc='center', ncol=1)
show()
uj5u.com熱心網友回復:
在這種情況下,最簡單的方法是創建自定義圖例。
一些注意事項:
plt.tight_layout()可用于將圖例和標簽很好地融入情節;這比 靈活得多fig.subplots_adjust(),尤其是在以后對繪圖進行更改時fig.legend()使用“當前斧頭”(當前子圖),在這種情況下是axes[2]- 將圖例放在圖的右側時,有助于使用
loc='upper left'錨點;不在左側的“loc”值太難控制(bbox_to_anchor設定錨點的位置,以給定子圖的
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/438506.html標籤:Python matplotlib 传奇 子情节
