gpt4 book ai didi

python - 直方图的颜色和标签不一致

转载 作者:行者123 更新时间:2023-12-01 08:26:03 28 4
gpt4 key购买 nike

我正在尝试分析wine-quality数据集。有两个数据集:红酒数据集和白 Wine 数据集。我将它们组合在一起形成 wine_df。我想绘制它。我想给红色直方图红色,白色直方图白色。但对于某些直方图,其标签和颜色不一致。例如,第四个标签是(4,白色),而其颜色是红色。我应该怎么办?感谢您的回答!

enter image description here

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns

red_wine = pd.read_csv('https://raw.githubusercontent.com/nishanthgandhidoss/Wine-Quality/master/data/winequality-red.csv',
sep = ';')
white_wine = pd.read_csv('https://raw.githubusercontent.com/nishanthgandhidoss/Wine-Quality/master/data/winequality-white.csv',
sep = ';')

## Add a column to each data to identify the wine color
red_wine['color'] = 'red'
white_wine['color'] = 'white'

## Combine the two dataframes
wine_df = pd.concat([red_wine, white_wine])

colors = ['red','white']
plt.style.use('ggplot')
counts = wine_df.groupby(['quality', 'color']).count()['pH']
counts.plot(kind='bar', title='Counts by Wine Color and quality', color=colors, alpha=.7)
plt.xlabel('Quality and Color', fontsize=18)
plt.ylabel('Count', fontsize=18)
plt.show()


最佳答案

颜色是索引的一个级别,因此请使用它来指定颜色。将代码行更改为:

counts.plot(kind='bar', title='Counts by Wine Color and quality', 
color=counts.index.get_level_values(1), alpha=.7)

enter image description here

<小时/>

在这种情况下,结果表明 matplotlib 可以将索引中的值解释为颜色。一般来说,您可以将唯一值映射到可识别的颜色,例如:

color = counts.index.get_level_values(1).map({'red': 'green', 'white': 'black'})

enter image description here

<小时/>

pandas 正在按照绘图顺序执行某些操作,但您始终可以回退到 matplotlib 来更可靠地循环颜色。这里的技巧是将 color 转换为分类变量,以便它始终在 groupby 之后表示,允许您仅指定列表 ['red', 'white' ]

import matplotlib.pyplot as plt

wine_df['color'] = wine_df.color.astype('category')
counts = wine_df.groupby(['quality', 'color']).count()['pH'].fillna(0)

ind = np.arange(len(counts))
plt.bar(ind, height=counts.values, color=['red', 'white'])
_ = plt.xticks(ind, counts.index.values, rotation=90)
plt.ylim(0,150) # So we an see (9, white)
plt.show()

enter image description here

关于python - 直方图的颜色和标签不一致,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54246799/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com