【问题标题】:Changing color scale/gradient vertically in bar like plot using seaborn使用seaborn在条形图中垂直更改颜色比例/渐变
【发布时间】:2018-09-01 07:57:00
【问题描述】:

我想为 seaborn barplot/countplot 的每个条设置垂直渐变,
(来源:pydata.org

#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 的示例 垂直渐变 忽略背景,颜色无关紧要。

附言新手到seaborn

【问题讨论】:

    标签: python plot seaborn


    【解决方案1】:

    我基于 ImportanceOfBeingErnest 的回答 using good old fashioned Matplotlib。基本上循环通过 Seaborn 的计数图中的酒吧容器,并使用带有渐变的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 计数图的输出:

    带有垂直渐变条的输出:

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-05-03
      • 1970-01-01
      • 2018-06-20
      • 2021-05-25
      • 2022-08-15
      • 1970-01-01
      • 2012-08-26
      相关资源
      最近更新 更多