我正在使用以下方式處理線圖:
x = np.arange(25,55,5)
y = np.random.randint(10000,50000,6)
y2 = np.random.randint(10000,60000,6)
然后主要的繪圖代碼是:
plt.style.use('fivethirtyeight')
plt.xlabel("some random ages")
plt.ylabel('some random salaries')
plt.title('whatever')
plt.legend(['first','second'])
plt.plot(x,y)
plt.plot(x,y2)
plt.fill_between(x,y,color = 'blue', alpha = 0.25, where = (y>np.median(y)), interpolate =True,
label = 'above median')
#Colour blue for salaries more than the median.
plt.fill_between(x,y,color = 'red', alpha = 0.25, where = (y<=np.median(y)), interpolate =True,
label = 'below median')
#Colour red for salaries less than the median.
plt.show()
填充按預期作業,但情節圖例僅具有 plt.legend(). label 引數似乎在我正在觀看的教程視頻以及我見過的所有其他網站中都有效,但并未將預期的標簽添加到圖例中。我在堆疊圖中遇到了同樣的問題,使用 pycharm 的導師曾經在 satckplotlabels中添加圖例,我不得不使用plt.legend,因為該labels命令似乎什么也沒做。但是在這里我不知道如何添加填充顏色的圖例以及主線圖的圖例。
我在 macOS Monterey 12.4 上使用最新版本的 jupyter notebook 和最新的 python 版本。
uj5u.com熱心網友回復:
label在所有地方指定您的 s :
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
x = np.arange(25,55,5)
y = np.random.randint(10000,50000,6)
y2 = np.random.randint(10000,60000,6)
plt.style.use('fivethirtyeight')
plt.plot(x,y, label='red')
plt.plot(x,y2, label='blue')
#Colour blue for salaries more than the median.
plt.fill_between(x,y,color = 'blue', alpha = 0.25, where = (y>np.median(y)), interpolate =True,
label = 'above median')
#Colour red for salaries less than the median.
plt.fill_between(x,y,color = 'red', alpha = 0.25, where = (y<=np.median(y)), interpolate =True,
label = 'below median')
plt.xlabel("some random ages")
plt.ylabel('some random salaries')
plt.title('whatever')
plt.legend()
plt.show()
或在圖例引數中指定所有標簽:
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(0)
x = np.arange(25,55,5)
y = np.random.randint(10000,50000,6)
y2 = np.random.randint(10000,60000,6)
plt.style.use('fivethirtyeight')
plt.plot(x,y)
plt.plot(x,y2)
#Colour blue for salaries more than the median.
plt.fill_between(x,y,color = 'blue', alpha = 0.25, where = (y>np.median(y)), interpolate =True)
#Colour red for salaries less than the median.
plt.fill_between(x,y,color = 'red', alpha = 0.25, where = (y<=np.median(y)), interpolate =True)
plt.xlabel("some random ages")
plt.ylabel('some random salaries')
plt.title('whatever')
plt.legend(['red', 'blue', 'above', 'below'])
plt.show()

請注意,第一種方法是推薦的方法(如 @JohanC 所述),因為它會為您完成作業并自動添加標簽。在第二個中,您正在覆寫圖例中的內容。這就是您的示例中發生的情況-您在label引數中定義了標簽,然后將串列傳遞給legend覆寫您label的 s.
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/495134.html
標籤:Python matplotlib
下一篇:如何為熊貓圖分組著色
