英文:
Setting xticks moves all bars to the left side of the figure
问题
我正在尝试设置每10年的x轴刻度标签。然而,当设置x轴刻度范围时,所有的条形图都压缩到了图形的左侧。
DataFrame示例
温度 年份
0 82 1900
1 52 1901
2 33 1902
3 91 1903
4 44 1904
代码
import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
# 随机样本数据
np.random.seed(365)
df = pd.DataFrame({'温度': np.random.randint(0, 100, 124), '年份': range(1900, 2024)})
# 根据最小和最大年份设置xticks
sns.barplot(data=df, x='年份', y='温度')
_ = plt.xticks(range(df.年份.min(), df.年份.max(), 10))
如何修复条形图,使x轴标签具有正确的范围,并且条形图的位置正确?
英文:
I'm trying to set the x-ticks labels for every 10 years. However, when the x-ticks range is set, all of the bars are compressed to the left side of the figure.
DataFrame Sample
Temperature Year
0 82 1900
1 52 1901
2 33 1902
3 91 1903
4 44 1904
Code
import pandas as pd
import seaborn as sns
import numpy as np
import matplotlib.pyplot as plt
# random sample data
np.random.seed(365)
df = pd.DataFrame({'Temperature': np.random.randint(0, 100, 124), 'Year': range(1900, 2024)})
# setting xticks based on the min and max year
sns.barplot(data=df, x='Year', y='Temperature')
_ = plt.xticks(range(df.Year.min(), df.Year.max(), 10))
How can I fix the barplot so the x-axis labels have the correct range, and the bars are positioned correctly?
答案1
得分: 1
-
seaborn.barplot
的坐标轴刻度以及pandas.DataFrame.plot
使用kind='bar'
的情况下,都是从0开始索引的。xtick标签只是文本,不代表刻度位置。 -
matplotlib.pyplot.bar
和matplotlib.axes.Axes.bar
根据传递给x轴的值进行索引,如果不是string
数据类型。 -
seaborn
是matplotlib
的高级API,而pandas.DataFrame.plot
默认使用matplotlib
作为后端。 -
对于水平条形图以及其他类别绘图方法,如
violinplot
、swarmplot
、stripplot
和boxplot
,也适用相同的规则。 -
使用
plt.gca().get_xticklabels()
或ax.get_xticklabels()
可以显示刻度和相关标签。 -
将xtick范围设置为从0到
len(df)
。
# 根据刻度值为0的索引设置xticks
# 颜色设置为单一颜色,因为husl颜色不包含任何信息
sns.barplot(data=df, x='Year', y='Temperature', color='tab:blue', width=0.3)
_ = plt.xticks(range(0, len(df), 12))
df.plot(kind='bar', x='Year', rot=0)
_ = plt.xticks(range(0, len(df), 12))
plt.bar(height='Temperature', x='Year', data=df)
_ = plt.xticks(range(df.Year.min(), df.Year.max() + 1, 10))
- 这同样适用于其他类别绘图:
violinplot
、swarmplot
、stripplot
、boxplot
和水平barplot
。
flights = sns.load_dataset('flights')
fig, ax = plt.subplots(2, 3, figsize=(12, 8), sharex=False, sharey=False, tight_layout=True)
ax = ax.flat
sns.violinplot(data=flights, x='year', y='passengers', color='tab:pink', ax=ax[0])
ax[0].set_xticks(range(0, len(df.year.unique()), 2))
sns.swarmplot(data=flights, x='year', y='passengers', size=3, ax=ax[1])
ax[1].set_xticks(range(0, len(df.year.unique()), 2))
sns.stripplot(data=flights, x='year', y='passengers', size=3, ax=ax[2])
ax[2].set_xticks(range(0, len(df.year.unique()), 2))
sns.boxplot(data=flights, x='year', y='passengers', color='tab:pink', ax=ax[3])
ax[3].set_xticks(range(0, len(df.year.unique()), 2))
sns.barplot(data=flights, y='year', x='passengers', color='tab:pink', orient='h', ax=ax[5])
ax[5].set_yticks(range(0, len(df.year.unique()), 2))
ax[4].remove()
plt.show()
英文:
- The axis ticks of a
seaborn.barplot
, and apandas.DataFrame.plot
withkind='bar'
, are indexed from0
. The xtick label is just text, and is not representative of the tick position.matplotlib.pyplot.bar
andmatplotlib.axes.Axes.bar
are indexed based on the value passed to the x-axis, if it's not astring
data type.seaborn
is a high-level API formatplotlib
, andpandas.DataFrame.plot
usesmatplotlib
as the default backend.- The same applies to horizontal bars, and to other categorical plot methods, such as
violinplot
,swarmplot
,stripplot
, andboxplot
.
- Using
plt.gca().get_xticklabels()
, orax.get_xticklabels()
, will show the ticks and the associated labels. - Set the xtick range from
0
to thelen(df)
.
# setting xticks based on the ticks being 0 indexed
# color was set to a single color, because the husl color did not encode any information
sns.barplot(data=df, x='Year', y='Temperature', color='tab:blue', width=0.3)
_ = plt.xticks(range(0, len(df), 12))
df.plot(kind='bar', x='Year', rot=0)
_ = plt.xticks(range(0, len(df), 12))
plt.bar(height='Temperature', x='Year', data=df)
_ = plt.xticks(range(df.Year.min(), df.Year.max() + 1, 10))
- This applies to other categorical plots:
violinplot
,swarmplot
,stripplot
,boxplot
, and horizontalbarplot
.
flights = sns.load_dataset('flights')
fig, ax = plt.subplots(2, 3, figsize=(12, 8), sharex=False, sharey=False, tight_layout=True)
ax = ax.flat
sns.violinplot(data=flights, x='year', y='passengers', color='tab:pink', ax=ax[0])
ax[0].set_xticks(range(0, len(df.year.unique()), 2))
sns.swarmplot(data=flights, x='year', y='passengers', size=3, ax=ax[1])
ax[1].set_xticks(range(0, len(df.year.unique()), 2))
sns.stripplot(data=flights, x='year', y='passengers', size=3, ax=ax[2])
ax[2].set_xticks(range(0, len(df.year.unique()), 2))
sns.boxplot(data=flights, x='year', y='passengers', color='tab:pink', ax=ax[3])
ax[3].set_xticks(range(0, len(df.year.unique()), 2))
sns.barplot(data=flights, y='year', x='passengers', color='tab:pink', orient='h', ax=ax[5])
ax[5].set_yticks(range(0, len(df.year.unique()), 2))
ax[4].remove()
plt.show()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论