在 Seaborn 热力图中将标题移到色条上方

7

我在 Seaborn 中制作了一个热力图,并有相应的水平颜色条。我已经为颜色条添加了标题,但实际上这个标题出现在颜色条下方,而我希望它出现在上方。是否有一些方法可以更改这个问题?并且是否能够更改标题的字体大小以及颜色条标签的大小?

fig, ax = plt.subplots(figsize=(30,12))
graph = sns.heatmap(df_pivot, cmap="Blues", linecolor="white", linewidths=0.1, 
            cbar_kws={"orientation": "horizontal", "shrink":0.40, "aspect":40, "label": "Number of accidents"})


ax.set_title("Number of traffic accidents per day & hour combination", 
fontsize=30, fontweight="bold")

from matplotlib import rcParams
rcParams['axes.titlepad'] = 70 # Space between the title and graph

locs, labels = plt.yticks() # Rotating row labels
plt.setp(labels, rotation=0) # Rotating row labels

ax.xaxis.tick_top() # x axis on top
ax.xaxis.set_label_position('top')

graph.tick_params(axis='both',labelsize=15) # Tick label size
graph

目前看起来是这个样子的。我希望“事故数量”标题在色条上方,但在热图下方。我希望色条与热图同宽。

enter image description here

1个回答

5

请像这个例子一样在单独的绘图中绘制您的色条。有关更多信息,请阅读注释:

import matplotlib.pyplot as plt
import numpy as np; np.random.seed(0)
import seaborn as sns; sns.set()

flights = sns.load_dataset("flights")
flights = flights.pivot("month", "year", "passengers")

# set height ratios of heatmap and coresponding colorbar
# hspace shows space between plots
# adjust hspace to put your title of colorbar correctly
grid_kws = {"height_ratios": (.9, .05), "hspace": .15}
f, (ax, cbar_ax) = plt.subplots(2, gridspec_kw=grid_kws, figsize=(30,12))
ax = sns.heatmap(flights, ax=ax,
    cbar_ax=cbar_ax,
    cbar_kws={"orientation": "horizontal","label": "Number of accidents"})

# set title and set font of title
ax.set_title("Number of traffic accidents per day & hour combination", 
fontsize=30, fontweight="bold")

# set font size of colorbar labels
cbar_ax.tick_params(labelsize=25) 

plt.show()

enter image description here


我看到你在这里做了什么,但我不想移动“每天和每小时交通事故数量组合”的标题,那个应该在热力图上方。我想要的是“事故数量”标题在色条上方,也就是与上面图片中“每天和每小时交通事故数量组合”所在位置相同。 - Kara W
将坐标轴 ax 的标题命名为 ax,而不是 cbar_ax - Serenity
但这又回到了最初的状态 - 正是我最开始的样子。我希望“事故数量”标题在色条上方,并且y轴标签(星期几)是水平的... - Kara W

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接