如何在seaborn直方图上将x轴值居中?

huangapple go评论74阅读模式
英文:

How to center x axis values on seaborn histogram?

问题

我知道当discrete = True时,x轴数值会对齐在中心。然而,我不明白为什么在创建具有特定柱数的直方图时会出现问题(例如,当设置柱数为19时):

sns.histplot(data=df_ckd, x="HEIGHT", hue="SEX", multiple="stack", bins=19)
plt.xticks(np.arange(32, 198, 12))
plt.show()

我该如何将这些x轴数值放在中心位置?

英文:

I know that when discrete = True, x-axis values are aligned on the center. However, I don't understand why it brakes when it comes to creating histogram with certain bin number (e.g., when setting a bins value of 19):

sns.histplot(data=df_ckd, x="HEIGHT", hue="SEX", multiple="stack",bins=19)
plt.xticks(np.arange(32, 198, 12))
plt.show()

How can I put those x axis values in the center?

如何在seaborn直方图上将x轴值居中?

答案1

得分: 1

你可以,但你必须先计算一些值。

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

penguins = sns.load_dataset("penguins")
penguins = penguins.dropna()

max_n = penguins.flipper_length_mm.max()
min_n = penguins.flipper_length_mm.min()
bins = 15
step = (max_n - min_n) / bins
print(min_n, max_n, bins, step)
# 172.0 231.0 15 3.933333333333333

arr_div = np.arange(min_n + step / 2, max_n + step / 2, step=step)
arr_div_r = np.round(arr_div, 0).astype(int)

sns.histplot(data=penguins, x="flipper_length_mm", hue="sex", bins=bins, multiple="stack")
plt.xticks(arr_div, arr_div_r)
# 若要查看未经四舍五入的真实值
# plt.xticks(arr_div)

plt.show()

如何在seaborn直方图上将x轴值居中?

英文:

You can, but you have to calculate some values first.

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

penguins = sns.load_dataset("penguins")
penguins = penguins.dropna()

max_n = penguins.flipper_length_mm.max()
min_n = penguins.flipper_length_mm.min()
bins = 15
step = (max_n - min_n) / bins
print(min_n, max_n, bins, step)
# 172.0 231.0 15 3.933333333333333

arr_div = np.arange(min_n + step / 2, max_n + step / 2, step=step)
arr_div_r = np.round(arr_div, 0).astype(int)

sns.histplot(data=penguins, x="flipper_length_mm", hue="sex", bins=bins, multiple="stack")
plt.xticks(arr_div, arr_div_r)
# To see the real values without rounding
# plt.xticks(arr_div)

plt.show()

如何在seaborn直方图上将x轴值居中?

答案2

得分: 0

你可以使用 xlim,例如:

import matplotlib.pyplot as plt
import seaborn as sns

data = [5, 8, 12, 18, 19, 19.9, 20.1, 21, 24, 28]

fig, ax = plt.subplots()
sns.histplot(data, ax=ax)  # distplot 已弃用,被 histplot 取代
ax.set_xlim(1, 31)
ax.set_xticks(range(1, 32))
plt.show()
英文:

You can use xlim, example:

import matplotlib.pyplot as plt
import seaborn as sns

data = [5,8,12,18,19,19.9,20.1,21,24,28] 

fig, ax = plt.subplots()
sns.histplot(data, ax=ax)  # distplot is deprecate and replaced by histplot
ax.set_xlim(1,31)
ax.set_xticks(range(1,32))
plt.show()

huangapple
  • 本文由 发表于 2023年2月19日 20:08:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/75500036.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定