【问题标题】:How to control the color of a specific column in a bar plot depending on it's xtick label?如何根据 xtick 标签控制条形图中特定列的颜色?
【发布时间】:2021-01-18 15:04:15
【问题描述】:

我有许多图表显示从语音到文本引擎的转录文本,我想在其中显示 S2T 引擎正确转录的条形图。我已根据子图的预期值标记了子图,现在想将引擎正确转录的条着色为与其他条不同的数字。

这意味着我需要根据它们的 x-tick 标签访问条形的颜色。我该怎么做?

基本上:

for xlabel in fig.xlabels:
   if(xlabel.text == fig.title):
      position = xlabel.position
      fig.colorbar(position, 'red')

用于生成绘图的代码:

def count_id(id_val, ax=None):
    title = df.loc[df['ID'] == id_val, 'EXPECTED_TEXT'].iloc[0]
    fig = df[df['ID']==id_val]['TRANSCRIPTION_STRING'].value_counts().plot(kind='bar', ax=ax, figsize=(20,6), title=title)
    fig.set_xticklabels(fig.get_xticklabels(), rotation=40, ha ='right')    
    fig.yaxis.set_major_locator(MaxNLocator(integer=True))

fig, axs = plt.subplots(2, 4)
fig.suptitle('Classic subplot')
fig.subplots_adjust(hspace=1.4)

count_id('byte', axs[0,0])
count_id('clefting', axs[0,1])
count_id('left_hander', axs[0,2])
count_id('leftmost', axs[0,3])
count_id('right_hander', axs[1,0])
count_id('rightmost', axs[1,1])
count_id('wright', axs[1,2])
count_id('write', axs[1,3])

如果有人知道如何迭代axs,这样我就不必调用count_id() 8 次,那也很有帮助。是的,我试过了:

misses = ['byte', 'cleftig', 'left_hander', 'leftmost', 'right_hander', 'rightmost', 'wright', 'write']

for ax, miss in zip(axs.flat, misses):
   count_id(ax, miss) # <- computer says no

【问题讨论】:

  • 设置条形的颜色时,您可以只传递一种颜色(所有条形都相同)或包含每个标签颜色的数组。示例:stackoverflow.com/a/59578106/9142735
  • 我的意思是,是的,但是有没有办法在初始化 plt.plot() 后访问颜色属性?
  • 哦,我不确定你可以。除了使用 DataFrame.plot 创建图形,您可以直接使用 matplotlib 的 plt.bar 并在创建每个绘图时将您的颜色数组传递给它(如上例所示)。

标签: python pandas matplotlib


【解决方案1】:

您可以在绘制条形之前和之后根据标签设置每个条形的颜色。

我将使用下面的示例数据进行演示。

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
data = pd.DataFrame({'word': list('abcdefg'), 'number': np.arange(1, 8)})

1.绘制之前: 这是绘制彩色条形图的最常用方法。您可以将颜色列表传递给plt.plot()

def plot_color_label_before(data, target):
    colors = ['red' if word == target else 'blue' for word in data.word]
    bars = plt.bar(x=data.word, height=data.number, color=colors, alpha=0.5)

传递给函数的data 包含两列,第一列列出了xtick 上的所有单词,第二列列出了相应的数字。 target 是您的预期单词。 代码根据是否与您的目标一致来确定每个单词的颜色。例如,

plot_color_label_before(data, 'c')

2。绘制后: 如果您想在调用plt.plot 后访问颜色,请使用set_color 更改特定条的颜色。

def plot_color_label_after(data, target):
    bars = plt.bar(x=data.word, height=data.number, color='blue', alpha=0.5)
    for idx, word in enumerate(data.word):
        if word == target:
            bars[idx].set_color(c='yellow')

plt.bar 返回一个BarContainer,它的第 i 个元素是一个补丁(矩形)。如果单词命中目标,则遍历所有标签并更改颜色。 例如,

plot_color_label_after(data, 'c')

最后,对于axs的迭代,只需解开它就可以解决问题。

fig, axs = plt.subplots(2, 4)
for ax in axs.ravel():
    ax.plot(...)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-10
    • 1970-01-01
    • 1970-01-01
    • 2021-09-24
    • 1970-01-01
    • 1970-01-01
    • 2020-03-22
    相关资源
    最近更新 更多