簡體   English   中英

在條形圖中突出顯示特定的條形

[英]Highlight particular bars in bar graph

我有兩個數據df1df2 df2df1子集。 我想繪制已確定df2行(不同的條形或其他顏色)的df1水平條形圖。 謝謝。

%matplotlib inline 
import pandas as pd
import matplotlib as plt

d1 = {
    'index' : [1, 2, 3, 4, 5], 
    'col1'  : [5, 8, 6, 4, 2]
}

d2 = {
    'index' : [3, 5], 
    'col1'  : [6, 2]
}

df1 = pd.DataFrame(d1).set_index(["index"])
df2 = pd.DataFrame(d2).set_index(["index"])

df1.plot(kind="barh", grid=False)

我認為解決方法是連接數據框並為缺失值附加nans

import pandas as pd
import matplotlib.pyplot as plt

d1 = {
    'index' : [1, 2, 3, 4, 5], 
    'col1'  : [5, 8, 6, 4, 2]
}

d2 = {
    'index' : [3, 5], 
    'col1'  : [6, 2]
}

df1 = pd.DataFrame(d1).set_index(["index"])
df2 = pd.DataFrame(d2).set_index(["index"])

plotThis = pd.concat([df1, df2], axis = 1, ignore_index = True)

plotThis.plot(kind = 'barh')

不幸的是,熊貓的barh功能不能讓我們為每個barh選擇不同的顏色。 但是既然如此 ,我將選擇使用pandas繪圖功能,而是直接使用matplotlib的功能。

在這種情況下,有很多方法可以達到期望的結果。 這是一個選擇:

fig, ax = plt.subplots()
c = ['C2' if i in df2.index else 'C1' for i in df1.index]
ax.barh(y=df1.index,width=df1.col1,color=c)
ax.grid(False)

在此處輸入圖片說明

@GlobalTraveler的答案讓我想到了另一個解決方案

df3 = df1.loc[df1.index.difference(df2.index)].append(df2, sort=False).sort_index()
df3.plot(kind='barh', stacked=True, grid=False)

第一行創建一個具有以下內容的新數據框:

    col1    col2
index       
1   5.0     NaN
2   8.0     NaN
3   NaN     6.0
4   4.0     NaN
5   NaN     2.0

繪制此數據幀將產生所需的輸出。 在此處輸入圖片說明

暫無
暫無

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

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