英文:
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?
答案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()
英文:
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()
答案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()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论