python - 如何在条形图上显示自定义值

标签 python pandas matplotlib seaborn bar-chart

我正在寻找如何在 Seaborn 中做两件事,即使用条形图显示数据框中的值,但不在图表中。

  1. 我希望在数据框中显示一个字段的值,同时绘制另一个字段的图表。例如,在下面,我正在绘制“小费”图形,但我想将 “total_bill” 的值置于每个条形图上方的中心位置(即周五上方 325.88,周六上方 1778.40,等等。 )
  2. 有没有办法缩放条形的颜色,'total_bill' 的最低值具有最浅的颜色(在本例中为星期五),而 'total_bill 的最高值' 有最黑的吗?显然,在进行缩放时我会坚持使用一种颜色(即蓝色)。

虽然我看到其他人认为这是另一个(或两个)问题的重复,但我遗漏了我如何使用不在图表中的值作为标签或阴影基础的部分。怎么说呢,以total_bill为依据。抱歉,根据这些答案我无法弄清楚。

从以下代码开始,

import pandas as pd
import seaborn as sns
%matplotlib inline

df = pd.read_csv("https://raw.githubusercontent.com/wesm/pydata-book/1st-edition/ch08/tips.csv", sep=',')
groupedvalues = df.groupby('day').sum().reset_index()
g = sns.barplot(x='day', y='tip', data=groupedvalues)

我得到以下结果:

Enter image description here

临时解决方案:

for index, row in groupedvalues.iterrows():
    g.text(row.name, row.tip, round(row.total_bill, 2), color='black', ha="center")

Enter image description here

阴影上,使用下面的示例,我尝试了以下操作:

import pandas as pd
import seaborn as sns
%matplotlib inline

df = pd.read_csv("https://raw.githubusercontent.com/wesm/pydata-book/1st-edition/ch08/tips.csv", sep=',')
groupedvalues = df.groupby('day').sum().reset_index()

pal = sns.color_palette("Greens_d", len(data))
rank = groupedvalues.argsort().argsort()
g = sns.barplot(x='day', y='tip', data=groupedvalues)

for index, row in groupedvalues.iterrows():
    g.text(row.name, row.tip, round(row.total_bill, 2), color='black', ha="center")

但这给了我以下错误:

AttributeError: 'DataFrame' object has no attribute 'argsort'

所以我尝试了一个修改:

import pandas as pd
import seaborn as sns
%matplotlib inline

df = pd.read_csv("https://raw.githubusercontent.com/wesm/pydata-book/1st-edition/ch08/tips.csv", sep=',')
groupedvalues = df.groupby('day').sum().reset_index()

pal = sns.color_palette("Greens_d", len(data))
rank = groupedvalues['total_bill'].rank(ascending=True)
g = sns.barplot(x='day', y='tip', data=groupedvalues, palette=np.array(pal[::-1])[rank])

剩下的就是

IndexError: index 4 is out of bounds for axis 0 with size 4

最佳答案

matplotlib 3.4.0 的新特性

现在有一个内置的 Axes.bar_label自动标记条形容器:

  • 对于单组条形图,传递单条容器:

    ax = sns.barplot(x='day', y='tip', data=groupedvalues)
    ax.bar_label(ax.containers[0])
    

    seaborn bar plot labeled

  • 对于多组条形图(使用hue),迭代多个条形容器:

    ax = sns.barplot(x='day', y='tip', hue='sex', data=df)
    for container in ax.containers:
        ax.bar_label(container)
    

    seaborn grouped bar plot labeled

更多详情:


颜色排序版

Is there a way to scale the colors of the bars, with the lowest value of total_bill having the lightest color (in this case Friday) and the highest value of total_bill having the darkest?

  1. 找出每个 total_bill 值的排名:

    • 要么使用Series.sort_values :

      ranks = groupedvalues.total_bill.sort_values().index
      # Int64Index([1, 0, 3, 2], dtype='int64')
      
    • 或压缩 Ernest 的 Series.rank链接版本 Series.sub :

      ranks = groupedvalues.total_bill.rank().sub(1).astype(int).array
      # [1, 0, 3, 2]
      
  2. 然后使用 ranks 重新索引调色板:

    palette = sns.color_palette('Blues_d', len(ranks))
    ax = sns.barplot(x='day', y='tip', palette=np.array(palette)[ranks], data=groupedvalues)
    

    seaborn bar plot color-ranked

关于python - 如何在条形图上显示自定义值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43214978/

相关文章:

python - Django:在我的模型中使用标准 Auth 库

python - 如何在 python 日志中插入换行符?

python - 收到错误 400 : redirect_uri_mismatch when trying to use OAuth2 with Google Sheets from a Django view

python - 如何使用 python 列表有效地重命名数据帧索引?

python - 仅从数据框中获取前三个值

python-2.7 - 视差图教程 SADWindowSize 和图像不能 float

python - 定义堆积条形图中每个条形的底部

python - python中的os.open和os.fdopen有什么区别

python - 如何向热图添加第二个比例?

python - 如何将带有多个字符的定界符的 .text 解析为 pandas df?