簡體   English   中英

Matplotlip plot 分組數據條形圖增加x軸空間

[英]Matplotlip plot barchart of grouped data increase space of x-axis

我想用 gourped 數據制作一個條形圖,但我無法在 x 軸上的列之間獲得空格。 我嘗試將不同的圖形大小和寬度設置為 0.8,但這無濟於事。

我的代碼如下所示:

data = [['Tom', 'a'], ['Tom', 'a'],['nick', 'a'], ['juli', 'a'],['juli', 'a'],['juli', 'b'],['Simon', 'b'],['Tom', 'b'],['Sandra', 'a'],['Stefan', 'b'],['Johnny', 'a'],['Johnny', 'b'],['Johnny', 'b'],['Johnny', 'b']]
df = pd.DataFrame(data, columns=['name', 'category'])

ax= df.groupby('name')['category'].value_counts().unstack(0).plot(kind ="bar", width=1.0,figsize = (20, 8), align = 'center', color=['#F9986C', '#C9B265', 'blue', 'red', '#6ABFD0','#C4A5F6','yellow','#6BBCE5',
                                                                                                                               '#E791F6','maroon','green','indigo','teal','lime','darkslategrey','#B6B965','orange'])
plt.ylabel('Count',fontsize=23)
plt.xlabel('Category', fontsize=23)
plt.legend(bbox_to_anchor=(0.99, 0.99), loc='upper right', borderaxespad=0)
plt.show()

結果是: 陰謀

有什么建議么?

當前不支持更改組中各個條的寬度。 知道哪些柱屬於同一組也可能會很混亂,尤其是涉及空柱。

一個簡單的解決方法是將 edgecolor 設置為ec='white' (和lw=1 )。

或者您可以遍歷生成的條並更新它們的寬度:

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

data = [['Tom', 'a'], ['Tom', 'a'],['nick', 'a'], ['juli', 'a'],['juli', 'a'],['juli', 'b'],['Simon', 'b'],['Tom', 'b'],['Sandra', 'a'],['Stefan', 'b'],['Johnny', 'a'],['Johnny', 'b'],['Johnny', 'b'],['Johnny', 'b']]
df = pd.DataFrame(data, columns=['name', 'category'])

ax = df.groupby('name')['category'].value_counts().unstack(0).plot(kind ="bar", width=1.0,figsize = (20, 8), align = 'center', color=['#F9986C', '#C9B265', 'blue', 'red', '#6ABFD0','#C4A5F6','yellow','#6BBCE5',

                                                                                                                              '#E791F6','maroon','green','indigo','teal','lime','darkslategrey','#B6B965','orange'])
ax.set_ylabel('Count',fontsize=23)
ax.set_xlabel('Category', fontsize=23)
ax.legend(bbox_to_anchor=(0.99, 0.99), loc='upper right', borderaxespad=0)

factor = 0.9  # reduce the width to 90% of their given width
for bars in ax.containers:
    for bar in bars:
        x, y = bar.get_xy()
        w = bar.get_width()
        bar.set_width(w * factor)
        bar.set_xy((x+w * (1-factor)/2, y))

plt.tight_layout()
plt.show()

分組條形圖,改變單個圖的寬度

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM