【问题标题】:Can't set different colors for each bar when I put it on top of a clustergram当我把它放在集群图的顶部时,无法为每个条设置不同的颜色
【发布时间】:2019-03-04 22:23:57
【问题描述】:

这是我的示例,我无法定义不同的条形颜色......由于某种原因,所有颜色都是红色的。

import pandas as pd 
import seaborn as sns 
import matplotlib.pyplot as plt  
# initiliaze a dataframe with index and column names 
idf = pd.DataFrame.from_items([('A', [1, 2, 3]), ('B', [4, 5, 6]), ('C', 10, 
20, 30]), ('D', [14, 15, 16])], orient='index', columns=['x', > 'y', 'z'])
# Plot the clustermap which will be a figure by itself 
cax = sns.clustermap(idf, col_cluster=False, row_cluster=True)

# Get the column dendrogram axis 
cax_col_dend_ax = cax.ax_col_dendrogram.axes
# Plot the boxplot on the column dendrogram axis
idf.iloc[0,:].plot(kind='bar', ax=cax_col_dend_ax, color = ['r', 'g', 'b'])

# Show the plot 
plt.show()

【问题讨论】:

  • 使用matplotlib版本'2.2.2'对我来说效果很好

标签: python pandas matplotlib seaborn


【解决方案1】:

您的代码对我来说很好用。看来您使用的是旧的 python 版本,因为我有一个FutureWarning: from_items is deprecated.。虽然这是来自pandas,但您可能想要升级。尽管如此,您仍然可以按如下方式更改颜色

import matplotlib as mpl

# Your code here
ax1 = idf.iloc[0,:].plot.bar(ax=cax_col_dend_ax)
colors = ['r', 'g', 'b']
bars = [r for r in ax1.get_children() if isinstance(r, mpl.patches.Rectangle)]

for i, bar in enumerate(bars[0:3]):
    bar.set_color(colors[i])

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    • 2015-04-16
    • 1970-01-01
    相关资源
    最近更新 更多