【问题标题】:Seaborn align plots in subplotsSeaborn 在子图中对齐图
【发布时间】:2020-08-29 11:45:40
【问题描述】:

我正在使用 Seaborn 绘制 3 个 ghaphs。我想知道如何垂直对齐不同的图。

这是我目前的情节:

这是我的代码:

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

flatui = ["#636EFA", "#EF553B", "#00CC96", "#AB63FA"]

fig, ax = plt.subplots(figsize=(17, 7))    
plot=sns.lineplot(ax=ax,x="number of weeks", y="avg streams", hue="year", data=df, palette=flatui)

ax.yaxis.set_major_formatter(ticker.FuncFormatter(lambda x, pos: '{:,.2f}'.format(x/1000) + 'K'))

plot.set(title='Streams trend')
plot.xaxis.set_major_locator(ticker.MultipleLocator(2))

    

    
fig, ax =plt.subplots(1,2, figsize=(17,7))
plot = sns.barplot(x="Artist", y="Releases", data = result.head(10), ax=ax[0])
plot.set_xticklabels(
    plot.get_xticklabels(), 
    rotation=90, 
    horizontalalignment='center',
    fontweight='light',
    fontsize='x-large'

)
plot=sns.barplot(x="Artist", y="Streams", data = result.head(10), ax=ax[1])
plot.set_xticklabels(
    plot.get_xticklabels(), 
    rotation=90, 
    horizontalalignment='center',
    fontweight='light',
    fontsize='x-large'

)

基本上,我创建一个图形,在其中绘制趋势图,然后创建一个带有 2 个子图的图形,在其中绘制我的 2 个条形图。

我想做的是对齐趋势图和 2 个条形图。正如您可能在左侧注意到的那样,趋势图和第一个条形图未对齐,我想让这两个图从同一点开始(例如在趋势图和第二个条形图的结尾,其中 2 个图对齐)。

我该怎么做?

【问题讨论】:

  • 您能否确认您需要 2 个单独的数字,而不是 1 个带有 3 个子图的数字?
  • @DizietAsahi 是一样的。我创建了 2 个图形,因为我找不到让单个情节在子情节中占据 2 个“插槽”的方法。目标是在我的图像中显示上面的趋势图和下面的 2 个条形图

标签: python matplotlib data-visualization seaborn


【解决方案1】:

这是使用GridSpec的解决方案

fig = plt.figure()
gs0 = matplotlib.gridspec.GridSpec(2,2, figure=fig)

ax1 = fig.add_subplot(gs0[0,:])
ax2 = fig.add_subplot(gs0[1,0])
ax3 = fig.add_subplot(gs0[1,1])

sns.lineplot(ax=ax1, ...)
sns.barplot(ax=ax2, ...)
sns.barplot(ax=ax3, ...)

如果你有最新版本的matplotlib,也可以使用the new semantic figure composition engine

axd = plt.figure(constrained_layout=True).subplot_mosaic(
    """
    AA
    BC
    """
)

sns.lineplot(ax=axd['A'], ...)
sns.barplot(ax=axd['B'], ...)
sns.barplot(ax=axd['C'], ...)

【讨论】:

  • 完美运行。有没有办法在上图(趋势图)和条形图之间设置边距?它们彼此非常接近,我想将它们移低一点
  • 您可以调整参数hspace,您可以将其传递给GridSpec,或通过gridspec_kw= 传递给subplot_mosaic(),请参阅我的答案中的链接
猜你喜欢
  • 2021-03-10
  • 2021-04-24
  • 1970-01-01
  • 2020-07-17
  • 2012-05-24
  • 2020-08-22
  • 1970-01-01
  • 2021-01-31
  • 2017-10-05
相关资源
最近更新 更多