2016-11-02 118 views
0

我想要根據預定義的顏色組中的給定值選擇酒吧的顏色。 「pahse」值決定了顏色。它被分成3個範圍並且範圍是排名的。 Rank用於調用調色板中的顏色。這部分工作正常。但我堅持使用彩條。 Colorbar應該包含基於字典「rank_classes」和tiks/labels的關鍵字的顏色,這些關鍵字基於用於排名的值。我試過matplotlib的mpl.colorbar.ColorbarBase(),但它似乎不喜歡海鳥sns.cubehelix_palette()。我想知道如何把這兩件事情合起來或者有更直接的解決方案?當酒吧顏色被選中時,barplot的顏色條

import pandas as pd 
import numpy as np 
import matplotlib.pyplot as plt 
import seaborn as sns 
sns.set_style("white") 
#%matplotlib inline 

index = ['25', '26', '27'] 
count = [10, 50, 22] 
phase = [0.9, 2.2, 1.2] 
ranks = [0, 2, 1] 

rank_classes = {0:"Ph<1", 1:"1<Ph<1.2", 2:"Ph>=1.2"} 

d = {'count' : pd.Series(count, index=index), 
    'phase' : pd.Series(phase, index=index), 
    'rank' : pd.Series(ranks, index=index) 
    } 

df = pd.DataFrame(d) 

# barplot 
fig, ax = plt.subplots() 
pal = sns.cubehelix_palette(3) 

x = df.index 
y = list(df['count']) 
z = list(df['rank']) 

sns.barplot(x=x, y=y, palette=np.array(pal)[z]) 
sns.despine() 
+0

你的意思是這樣http://stackoverflow.com/questions/31313606/pyplot-matplotlib-bar-chart-with-fill-color-depending-on-value? – lanery

+0

@lanery 我看到了,訣竅是將兩個圖形放在彼此的頂部,並且只能從散點圖顯示顏色條。就我而言,我有兩個問題需要根據需要調整引用的代碼。 首先,我想使用具有預定義數量的顏色(如** sns.cubehelix_palette(3)**)的seaborn顏色方案。但是這種格式與plt.scatter()中的cmap不兼容。如何使其兼容? 第二,如何爲** sns.cubehelix_palette(3)中的第一,第二等...顏色分配預定義的字符串標籤(「A」,「B」,「Z」)**使用** plt.colobar ()**? – tonu

回答

1

幾乎有

import numpy as np 
import matplotlib as mpl 
import matplotlib.pyplot as plt 
import seaborn as sns 
sns.set_style("white") 
%matplotlib inline 

index = ['25', '26', '27'] 
count = [10, 50, 22] 
phase = [0.9, 2.2, 1.2] 
rank = [0, 2, 1] 
# 
rank_classes = {0:"Ph<1", 1:"1<Ph<1.2", 2:"Ph>=1.2"} 

pal = sns.cubehelix_palette(len(index)) 
cmp = mpl.colors.LinearSegmentedColormap.from_list('my_list', pal,\ 
                N=len(index)) 
plot = plt.scatter(index, count, c=range(len(index)), cmap=cmp) 
plt.clf() 
plt.colorbar(plot) 
sns.barplot(x=index, y=count, palette=np.array(pal)[rank]) 
sns.despine() 

主要生產好的情節與彩條。唯一需要弄清楚的是如何用字典rank_classes中列出的字符串替換colorbar的數字標籤(0,0.3 ... 3.0)。

Bar plot with colobar

+0

終於設法得到我所需要的基於: http://stackoverflow.com/questions/3831569/matplotlib-pyplot-colorbar-questions 和 http://stackoverflow.com/questions/15908371/matplotlib-colorbars-和它的文本的標籤 – tonu