Seaborn适用于色调条纹的解决方法

时间:2017-04-16 23:24:54

标签: python pandas matplotlib data-visualization seaborn

我在 Jupyter笔记本上有以下DataFrame,它使用seaborn绘制条形图:

    day_index   avg_duration    trips
0       0         708.852242    114586
1       1         676.702190    120936
2       2         684.572677    118882
3       3         708.925340    117868
4       4         781.767476    108036
5       5         1626.575057   43740
6       6         1729.155673   37508

daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday\n', \
'Friday', 'Saturday', 'Sunday']

plt.figure(figsize=(16,10));
sns.set_style('ticks')
ax = sns.barplot(data=dfGroupedAgg, \
                 x='day_index', \
                 y='avg_duration', \
                 hue='trips', \
                 palette=sns.color_palette("Reds_d", n_colors=7, desat=1))

ax.set_xlabel("Week Days", fontsize=18, alpha=0.8)
ax.set_ylabel("Duration (seconds)", fontsize=18, alpha=0.8)
ax.set_title("Week's average Trip Duration", fontsize=24)
ax.set_xticklabels(daysOfWeek, fontsize=16)
ax.legend(fontsize=15)
sns.despine()
plt.show()

情节A: enter image description here

可以看出,条形与x_ticklabels不匹配,非常薄 如果我删除了hue='trips'部分,这已经解决了,这是一个已知的seaborn问题。 虽然显示可视化中的行程量非常重要,但是:是否可以通过seaborn(可能直接使用matplotlib)来添加色调属性?

4 个答案:

答案 0 :(得分:2)

我认为在这种情况下您不需要指定hue参数:

In [136]: ax = sns.barplot(data=dfGroupedAgg, \
     ...:                  x='day_index', \
     ...:                  y='avg_duration', \
     ...:                  palette=sns.color_palette("Reds_d", n_colors=7, desat=1))
     ...:

您可以添加旅行量作为注释:

def autolabel(rects, labels=None, height_factor=1.05):
    for i, rect in enumerate(rects):
        height = rect.get_height()
        if labels is not None:
            try:
                label = labels[i]
            except (TypeError, KeyError):
                label = ' '
        else:
            label = '%d' % int(height)
        ax.text(rect.get_x() + rect.get_width()/2., height_factor*height,
                '{}'.format(label),
                ha='center', va='bottom')

autolabel(ax.patches, labels=df.trips, height_factor=1.02)

enter image description here

答案 1 :(得分:2)

hue参数可能只对图中引入新维度有意义,而不是在同一维度上显示另一个数量。

最好在没有hue参数的情况下绘制条形图(实际上将其称为色调是非常误导的),并根据"trips"列中的值简单地着色条形图。

此问题也显示在此问题:Seaborn Barplot - Displaying Values

这里的代码如下:

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

di = np.arange(0,7)
avg  = np.array([708.852242,676.702190,684.572677,708.925340,781.767476,
                 1626.575057,1729.155673])
trips = np.array([114586,120936,118882,117868,108036,43740,37508])
df = pd.DataFrame(np.c_[di, avg, trips], columns=["day_index","avg_duration", "trips"])

daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', \
'Friday', 'Saturday', 'Sunday']

plt.figure(figsize=(10,7));
sns.set_style('ticks')
v  = df.trips.values
colors=plt.cm.viridis((v-v.min())/(v.max()-v.min()))
ax = sns.barplot(data=df, x='day_index',   y='avg_duration', palette=colors)

for index, row in df.iterrows():
    ax.text(row.day_index,row.avg_duration, row.trips, color='black', ha="center")

ax.set_xlabel("Week Days", fontsize=16, alpha=0.8)
ax.set_ylabel("Duration (seconds)", fontsize=16, alpha=0.8)
ax.set_title("Week's average Trip Duration", fontsize=18)
ax.set_xticklabels(daysOfWeek, fontsize=14)
ax.legend(fontsize=15)
sns.despine()
plt.show()

enter image description here

答案 2 :(得分:0)

从颜色图构建图例

  • 删除hue。如前所述,使用此参数时,条形图不会居中,因为它们是根据色相级别数放置的,在这种情况下有7个级别。
  • 使用palette参数而不是hue,将条形图直接放在刻度上。
  • 此选项要求将'trips'与颜色“手动”关联并创建图例。
    • patches使用Patch创建图例中的每个项目。 (例如与颜色和名称相关联的矩形)。
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from matplotlib.patches import Patch

# plt styling parameters
plt.style.use('seaborn')
plt.rcParams['figure.figsize'] = (16.0, 10.0)
plt.rcParams["patch.force_edgecolor"] = True

daysOfWeek = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']

# specify the colors
colors = sns.color_palette('Reds_d', n_colors=len(df))

# create the plot
plt.figure(figsize=(16,10))
p = sns.barplot(data=df, x='day_index', y='avg_duration', palette=colors)

# plot cosmetics
p.set_xlabel("Week Days", fontsize=18, alpha=0.8)
p.set_ylabel("Duration (seconds)", fontsize=18, alpha=0.8)
p.set_title("Week's average Trip Duration", fontsize=24)
p.set_xticklabels(daysOfWeek, fontsize=16)
sns.despine()

# setup the legend

# map names to colors
cmap = dict(zip(df.trips, colors))

# create the rectangles for the legend
patches = [Patch(color=v, label=k) for k, v in cmap.items()]

# add the legend
plt.legend(title='Number of Trips', handles=patches, bbox_to_anchor=(1.04, 0.5), loc='center left', borderaxespad=0, fontsize=15)

enter image description here

答案 3 :(得分:0)

这是解决方案

ax = sns.barplot(data=df, \
                 x='day_index', \
                 y='avg_duration', \
                 hue='trips', \
                 dodge=False, \
                 palette=sns.color_palette("Reds_d", n_colors=7, desat=1))