[英]Problem to display negative values in grouped bar chart (matplotlib)
我有以下數據框:
Location Growth Growth_Zero_Migration
0 Africa 2939529.018 2998261.337
1 Asia 78852.134 256394.122
2 Australia/New Zealand 18563.010 -2212.990
3 Europe and Northern America 3945.429 -253849.105
4 South America -1459.056 3117.976
當我嘗試通過 matplot 顯示它(作為分組條形圖)時,並非所有負值都正確顯示。我發現這個解決方案Negative values bars on the same matplotlib chart ,但它對我沒有多大幫助 - 所有我的條獲得 y 的底部或頂部值我想我的問題是一個范圍(如您所見,它是 [-253849.105, 2998261.337],但我不知道如何對其進行規范化。任何提示將不勝感激。這是我的代碼和 output:
..........
def get_Table_For_Growth(columnName, fileName, variant, range):
pop_stat = pb.read_csv("WPP2019_TotalPopulationBySex.csv")
locations_table = pb.read_csv("{filename}.csv".format(filename=fileName))
table = pop_stat[(pop_stat['Variant'] == variant) & (pop_stat[columnName].isin(locations_table[columnName])) & (
(pop_stat['Time'] == range[0]) | (pop_stat['Time'] == range[1]))].loc[:, ['Location', 'PopTotal']]
table['Growth'] = table.groupby('Location')['PopTotal'].diff()
table = table.dropna()
table = table.reset_index(drop=True)
# table.style.hide_index()
table = table.sort_values(by='Growth', ascending=False)
del table['PopTotal']
return table
def show_graph(table, type, xcoor, ycoor, colour):
table.plot(kind=type, x=xcoor, y=ycoor, color=colour)
plt.show()
continents_zero_migration = get_Table_For_Growth("Location", "continents", "Zero migration", [2020, 2100])
continents_medium_vs_zero_migration = get_Table_For_Growth("Location", "continents", "Medium", [2020, 2100])
continents_medium_vs_zero_migration['Growth_Zero_Migration'] = continents_zero_migration['Growth']
continents_medium_vs_zero_migration = pb.DataFrame({'Growth Forecast': continents_medium_vs_zero_migration['Growth'].tolist(),
'Zero migration' : continents_medium_vs_zero_migration['Growth_Zero_Migration'].tolist()},
index = continents_medium_vs_zero_migration['Location'])
continents_medium_vs_zero_migration.plot.bar()
plt.show()
..........
我相信使用plt.yscale('symlog')
可以幫助您獲得所需的結果。
下面自包含的玩具示例代碼是您的代碼的簡化腳本:
import matplotlib.pyplot as plt
import pandas as pd
df = pd.DataFrame([['Africa',2939529.018,2998261.337],\
['Asia',78852.134,256394.122],\
['Australia/New Zealand',18563.010,-2212.990],\
['Europe and Northern America',3945.429,-253849.105],\
['South America',-1459.056,3117.976]], columns=['Location','Growth','Growth_Zero_Migration'])
ax = df.plot.bar()
plt.xticks(range(len(df)),df['Location'])
plt.yscale('symlog')
plt.xlabel('Location')
plt.show()
結果如下圖:
如您所見,它在 y 軸上以正負值進行對數縮放,您可以輕松查看整個數據。
在這種情況下,我建議在顯示圖表之前使用網格添加以下代碼:
plt.grid(True)
由於對數刻度范圍之間的值可能有很大差異。 結果圖將是:
導入pyplot:
import matplotlib.pyplot as plt
。
然后,嘗試在plt.show()
之前添加以下行
plt.gca().set_ylim(-3E6, 3E6)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.