使用seaborn在条形图中垂直改变色标/渐变

时间:2018-03-22 18:36:59

标签: python plot seaborn

我希望seaborn barplot / countplot的每个条形都有垂直渐变, horizontal gradient across bars

#to reproduce above plot
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns

sns.set(style="whitegrid", color_codes=True)
np.random.seed(sum(map(ord, "categorical")))
titanic = sns.load_dataset("titanic")
sns.countplot(x="deck", data=titanic, palette="Greens_d")
plt.show()

此图像具有水平渐变,但我希望渐变为垂直,例如Excel https://support.office.com/en-us/article/add-a-gradient-color-to-a-shape-11cf6392-723c-4be8-840a-b2dab4b2ba3e

中的线性向下或线性向上渐变

请参阅https://matplotlib.org/gallery/lines_bars_and_markers/gradient_bar.html中的示例 用于垂直渐变 Example of vertical gradient忽略背景,颜色无关紧要。

P.S。新手到seaborn

1 个答案:

答案 0 :(得分:0)

我基于using good old fashioned Matplotlib在ImportanceOfBeingErnest的回答。本质上是遍历Seaborn计数图中的bar容器,并使用带有渐变的imshow。希望这会有所帮助!

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

def gradientbars(bars):
    grad = np.atleast_2d(np.linspace(0,1,256)).T # Gradient of your choice

    rectangles = bars.containers[0]
    # ax = bars[0].axes
    fig, ax = plt.subplots()

    xList = []
    yList = []
    for rectangle in rectangles:
        x0 = rectangle._x0
        x1 = rectangle._x1
        y0 = rectangle._y0
        y1 = rectangle._y1

        xList.extend([x0,x1])
        yList.extend([y0,y1])

        ax.imshow(grad, extent=[x0,x1,y0,y1], aspect="auto", zorder=0)

    ax.axis([min(xList), max(xList), min(yList), max(yList)*1.1]) # *1.1 to add some buffer to top of plot

    return fig,ax


sns.set(style="whitegrid", color_codes=True)
np.random.seed(sum(map(ord, "categorical")))

# Load dataset
titanic = sns.load_dataset("titanic")

# Make Seaborn countplot
seabornAxHandle = sns.countplot(x="deck", data=titanic, palette="Greens_d")
plt.show() # Vertical bars with horizontal gradient

# Call gradientbars to make vertical gradient barplot using Seaborn ax
figVerticalGradient, axVerticalGradient = gradientbars(seabornAxHandle)

# Styling using the returned ax
axVerticalGradient.xaxis.grid(False)
axVerticalGradient.yaxis.grid(True)

# Labeling plot to match Seaborn
labels=titanic['deck'].dropna().unique().to_list() # Chaining to get tick labels as a list
labels.sort()
plt.ylabel('count')
plt.xlabel('deck')
plt.xticks(range(0,len(labels)), labels)  # Set locations and labels

plt.show() # Vertical bars with vertical gradient

Seaborn计数图的输出: Output from Seaborn countplot

带有垂直渐变条的输出: Output with gradient bars