设置xticks会将所有的柱子移到图的左侧。

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

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))

设置xticks会将所有的柱子移到图的左侧。

如何修复条形图,使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))

设置xticks会将所有的柱子移到图的左侧。

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.barmatplotlib.axes.Axes.bar根据传递给x轴的值进行索引,如果不是string数据类型。

  • seabornmatplotlib的高级API,而pandas.DataFrame.plot默认使用matplotlib作为后端。

  • 对于水平条形图以及其他类别绘图方法,如violinplotswarmplotstripplotboxplot,也适用相同的规则。

  • 使用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))

设置xticks会将所有的柱子移到图的左侧。

df.plot(kind='bar', x='Year', rot=0)
_ = plt.xticks(range(0, len(df), 12))

设置xticks会将所有的柱子移到图的左侧。

plt.bar(height='Temperature', x='Year', data=df)
_ = plt.xticks(range(df.Year.min(), df.Year.max() + 1, 10))

设置xticks会将所有的柱子移到图的左侧。


  • 这同样适用于其他类别绘图:
    • violinplotswarmplotstripplotboxplot和水平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()

设置xticks会将所有的柱子移到图的左侧。

英文:
  • The axis ticks of a seaborn.barplot, and a pandas.DataFrame.plot with kind='bar', are indexed from 0. The xtick label is just text, and is not representative of the tick position.
    • matplotlib.pyplot.bar and matplotlib.axes.Axes.bar are indexed based on the value passed to the x-axis, if it's not a string data type.
    • seaborn is a high-level API for matplotlib, and pandas.DataFrame.plot uses matplotlib as the default backend.
    • The same applies to horizontal bars, and to other categorical plot methods, such as violinplot, swarmplot, stripplot, and boxplot.
  • Using plt.gca().get_xticklabels(), or ax.get_xticklabels(), will show the ticks and the associated labels.
  • Set the xtick range from 0 to the len(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))

设置xticks会将所有的柱子移到图的左侧。

df.plot(kind='bar', x='Year', rot=0)
_ = plt.xticks(range(0, len(df), 12))

设置xticks会将所有的柱子移到图的左侧。

plt.bar(height='Temperature', x='Year', data=df)
_ = plt.xticks(range(df.Year.min(), df.Year.max() + 1, 10))

设置xticks会将所有的柱子移到图的左侧。


  • This applies to other categorical plots:
    • violinplot, swarmplot, stripplot, boxplot, and horizontal 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()

设置xticks会将所有的柱子移到图的左侧。

huangapple
  • 本文由 发表于 2023年6月1日 05:00:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76377236.html
匿名

发表评论

匿名网友

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

确定