我想在我的情節中添加一個圖例,其中包含所有 hline 的統計描述。有什么辦法嗎?def test_plot():Q1=test['age'].quantile(0.25)Q3=test['age'].quantile(0.75)IQR=Q3-Q1fig = ( ggplot(test) + aes(x=arr,y='age')+ geom_point()+ labs( title='Test', x='Index', y='Age', )+ geom_hline(aes(yintercept =test.age.mean(),),color = 'gray')+ geom_hline(aes(yintercept =test.age.median()),color = 'green')+ geom_hline(aes(yintercept =IQR),color = 'blue')+ geom_hline(aes(yintercept =test['age'].quantile(0.1)),color= 'red')+ geom_hline(aes(yintercept =test['age'].quantile(0.9)),color= 'yellow')+ geom_hline(aes(yintercept =test['age'].std()),color= 'purple') )
1 回答

青春有我
TA貢獻1784條經驗 獲得超8個贊
在大多數情況下,當您發現自己與圖例作斗爭時,這表明您正在繪制的數據沒有被有意義地排列。圖例旨在幫助解釋映射變量。在您的情況下,所有這些水平線都可以用一個變量表示,即“年齡統計”。
然后解決方案是將它們放入數據框中并使用一次調用,geom_hline以便繪圖系統可以處理圖例。
sdf = pd.DataFrame({
'age_statistic': [
'mean', 'median', IQR,
'10th Percentile', '90th Percentile',
'std'
],
'value' : [
test.age.mean(), test.age.median(), IQR,
test['age'].quantile(0.1), test['age'].quantile(0.9),
test['age'].std()
]
})
(ggplot(...)
...
+ geom_hline(sdf, aes(yintercept='value', colour='age_statistic'), show_legend=True)
)
添加回答
舉報
0/150
提交
取消