簡體   English   中英

Pandas DataFrame 條形圖 - 從特定顏色圖中繪制不同顏色的條形圖

[英]Pandas DataFrame Bar Plot - Plot Bars Different Colors From Specific Colormap

如何使用熊貓數據框plot方法繪制條形圖的條形圖不同顏色?

如果我有這個 DataFrame:

df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index()

   index  count
0      0   3372
1      1  68855
2      2  17948
3      3    708
4      4   9117

我需要設置什么df.plot()參數,以便圖中的每個條形:

  1. 使用“配對”顏色圖
  2. 為每個條繪制不同的顏色

我正在嘗試什么:

df.plot(x='index', y='count', kind='bar', label='index', colormap='Paired', use_index=False)

結果:

不是不同的顏色

我已經知道的(是的,這是可行的,但同樣,我的目的是弄清楚如何僅使用df.plot來做到這df.plot 。當然它必須是可能的?):

def f(df):
  groups = df.groupby('index')

  for name,group in groups:
    plt.bar(name, group['count'], label=name, align='center')

  plt.legend()
  plt.show()

最終結果但用於循環

沒有任何參數可以傳遞給df.plot以不同方式為單列着色條形。
由於不同列的條形顏色不同,一個選項是在繪圖之前轉置數據框,

ax = df.T.plot(kind='bar', label='index', colormap='Paired')

現在,這會將數據繪制為子組的一部分。 因此,需要應用一些調整來正確設置限制和 xlabels。

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index()

ax = df.T.plot(kind='bar', label='index', colormap='Paired')
ax.set_xlim(0.5, 1.5)
ax.set_xticks([0.8,0.9,1,1.1,1.2])
ax.set_xticklabels(range(len(df)))
plt.show()

在此處輸入圖片說明

雖然我猜這個解決方案符合問題的標准,但使用plt.bar實際上沒有任何問題。 一次調用plt.bar就足夠了

plt.bar(range(len(df)), df["count"], color=plt.cm.Paired(np.arange(len(df))))

在此處輸入圖片說明

完整代碼:

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

df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index()

plt.bar(range(len(df)), df["count"], color=plt.cm.Paired(np.arange(len(df))))

plt.show()

您可以根據需要使用參數color為每一列color

例如(例如,有 3 個變量):

df.plot.bar(color=['C0', 'C1', 'C2'])

注意:上面提到的字符串'C0', 'C1', ...'是 matplotlib 中內置的快捷顏色句柄。 它們表示活動配色方案中的第一個、第二個、第三個默認顏色,依此類推。 事實上,它們只是一個示例,您可以使用 RGB 代碼或任何其他顏色約定輕松使用任何自定義顏色。

您甚至可以突出顯示特定列,例如,此處的中間列:

df.plot.bar(color=['C0', 'C1', 'C0'])

要在給定的示例代碼中重現它,可以使用:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({'count': {0: 3372, 1: 68855, 2: 17948, 3: 708, 4: 9117}}).reset_index()

ax = df.T.plot(kind='bar', label='index', color=['C0', 'C1', 'C2', 'C3', 'C4'])
ax.set_xlim(0.5, 1.5)
ax.set_xticks([0.8,0.9,1,1.1,1.2])
ax.set_xticklabels(range(len(df)))
plt.show()

不同顏色的示例:

不同顏色的例子

任意重復顏色的示例:

任意重復顏色的示例

參考鏈接: 在熊貓中分配線條顏色

除了/擴展@Jairo Alves 工作,您還可以指明特定的十六進制代碼

df.plot(kind="bar",figsize=(20, 8),color=['#5cb85c','#5bc0de','#d9534f'])

在此處輸入圖片說明

暫無
暫無

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

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