我有一個類似于以下的資料集:
import pandas as pd
data = {'Country': ['Spain', 'Italy', 'France', 'Germany', 'Portugal', 'Greece', 'UK', 'Spain', 'Italy', 'France', 'Germany', 'Portugal', 'Greece', 'UK', 'Spain', 'Italy', 'France', 'Germany', 'Portugal', 'Greece', 'UK'],
'Date': ['Jan 2020', 'Jan 2020', 'Jan 2020', 'Jan 2020', 'Jan 2020', 'Jan 2020', 'Jan 2020', 'Feb 2020', 'Feb 2020', 'Feb 2020', 'Feb 2020', 'Feb 2020', 'Feb 2020', 'Feb 2020', 'Dec 2020', 'Dec 2020', 'Dec 2020', 'Dec 2020', 'Dec 2020', 'Dec 2020', 'Dec 2020'],
'Sales': [20000, 30000, 10000, 10000, 30000, 10000, 10000, 50000, 40000, 30000, 20000, 30000, 10000, 10000, 60000, 70000, 80000, 10000, 30000, 10000, 10000]}
df = pd.DataFrame(data)
Country Date Sales
0 Spain Jan 2020 20000
1 Italy Jan 2020 30000
2 France Jan 2020 10000
3 Germany Jan 2020 10000
4 Portugal Jan 2020 30000
5 Greece Jan 2020 10000
6 UK Jan 2020 10000
7 Spain Feb 2020 50000
8 Italy Feb 2020 40000
9 France Feb 2020 30000
10 Germany Feb 2020 20000
11 Portugal Feb 2020 30000
12 Greece Feb 2020 10000
13 UK Feb 2020 10000
14 Spain Dec 2020 60000
15 Italy Dec 2020 70000
16 France Dec 2020 80000
17 Germany Dec 2020 10000
18 Portugal Dec 2020 30000
19 Greece Dec 2020 10000
20 UK Dec 2020 10000
我想可視化一年中各個國家/地區的銷售額如何變化,因此我想顯示 7 個直方圖(每個國家/地區一個)。對于每個圖,“日期”將位于 x 軸上,“銷售額”值位于 y 軸上。此外,還需要用于標識國家/地區的標題以及 x 標簽、y 標簽。
我嘗試了之前討論中找到的幾個選項,但沒有一個適合我想要實作的目標。我嘗試了以下方法:
df.groupby('Country').hist(column='Sales', grid= False, figsize=(2,2))
df['Sales'].hist(grid=True, by=one_year_df['Country'])
df.groupby('Country').hist(grid= False, figsize=(2,2))
df.reset_index().pivot('index','Country','Sales').hist(grid=False, bins=12)
grouped = df.groupby('Country')
ncols=2
nrows = int(np.ceil(grouped.ngroups/ncols))
fig, axes = plt.subplots(nrows=nrows, ncols=ncols, figsize=(12,12), sharey=False)
for (key, ax) in zip(grouped.groups.keys(), axes.flatten()):
grouped.get_group(key).plot(ax=ax)
ax.legend()
plt.show()
但是,這些選項都沒有給我設定“日期”列的可能性,而且似乎無法按照我的意愿設定 x 軸、y 軸,因此,這些圖毫無意義。
我還發現了另一段代碼,它似乎考慮了所有變數,但結果仍然不如預期:
fig, ax = plt.subplots(figsize=(15,7))
df.groupby(['Country']).sum()['Sales'].plot(ax=ax)
ax.set_xlabel('Date')
ax.set_ylabel('Sales')
歡迎任何意見或建議。謝謝你。
uj5u.com熱心網友回復:
- 對于每個圖,“日期”將位于 x 軸上,“銷售額”值位于 y 軸上。最好用折線圖或條形圖顯示。直方圖本質上是條形圖(就可視化而言)。
- 將
'Date'列轉換為日期時間
- 如果繪制條形圖,則會出現擁擠的混亂,因為每行資料都會有一個條形。
ax = dfp.plot(kind='bar', subplots=True, figsize=(14, 12), layout=(2, 4), rot=0, legend=False)
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/374546.html標籤:Python 熊猫 matplotlib 阴谋 条形图
上一篇:避免在matplotlib中使用[[...],[...]...]形式的x,y重復標簽
下一篇:熊貓欄如何標記所需的值
