如何根据条形图的xtick标签控制其特定列的颜色?

2024-09-22 16:35:25 发布

您现在位置:Python中文网/ 问答频道 /正文

我有许多绘图,显示从语音到文本引擎转录的文本,我想在其中显示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

enter image description here


Tags: 引擎文本rightid绘图dftitlecount
1条回答
网友
1楼 · 发布于 2024-09-22 16:35:25

可以在打印条之前和之后根据标签设置每个条的颜色

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

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')

enter image description here

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')

enter image description here

最后,对于在axs上迭代,只需将其拉威尔即可解决问题

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

相关问题 更多 >