我嘗試使用 seaborn 和 matplotlib 繪制計數圖。給定每年,我想對每年的“干旱型別”計數進行排序,以使其看起來更好。目前它每年都沒有分類,看起來很亂。謝謝!
import seaborn as sns
import matplotlib.pyplot as plt
count=pd.read_csv(r"https://raw.githubusercontent.com/tuyenhavan/Course_Data/main/count.csv")
plt.figure(figsize=(15,8))
sns.countplot(x= 'Year', hue = 'Drought types', data = count, palette = 'YlOrRd')
plt.legend(loc = "best",frameon=True,bbox_to_anchor=(0.9,0.75))
plt.show()
uj5u.com熱心網友回復:
以下方法逐一繪制年份。 order=用于固定年份的順序。 hue_order為每一年重新計算(.reindex()需要確保所有干旱型別都存在)。
字典調色板用于確保每個色調值獲得相同的顏色,而與順序無關。自動圖例會重復每年的所有色調值,因此需要減少圖例。
順便說一下,loc='best'不應該bbox_to_anchor在圖例中與 with 一起使用,因為它可能會導致資料的微小變化引起非常意想不到的變化。loc='best'將根據可用空間更改為 9 個可能的位置之一。
import matplotlib.pyplot as plt
import seaborn as sns
import pandas as pd
count = pd.read_csv("https://raw.githubusercontent.com/tuyenhavan/Course_Data/main/count.csv")
fig, ax = plt.subplots(figsize=(15, 8))
drought_types = count['Drought types'].unique()
palette = {drought_type: color
for drought_type, color in zip(drought_types, sns.color_palette('YlOrRd', len(drought_types)))}
all_years = range(count['Year'].min(), count['Year'].max() 1)
sns.set_style('darkgrid')
for year in all_years:
year_data = count[count['Year'] == year]
if len(year_data) > 0:
# reindex is needed to make sure all drought_types are present
hue_order = year_data.groupby('Drought types').size().reindex(drought_types).sort_values(ascending=True).index
sns.countplot(x='Year', order=all_years,
hue='Drought types', hue_order=hue_order,
data=year_data, palette=palette, ax=ax)
# handles, _ = ax.get_legend_handles_labels()
# handles = handles[:len(drought_types)]
handles = [plt.Rectangle((0, 0), 0, 0, color=palette[drought_type], label=drought_type)
for drought_type in drought_types]
ax.legend(handles=handles, loc="upper right", frameon=True, bbox_to_anchor=(0.995, 0.99))
plt.show()

轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/433239.html
標籤:Python matplotlib 阴谋 jupyter-笔记本 海运
