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

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

Setting xticks moves all bars to the left side of the figure

问题

我正在尝试设置每10年的x轴刻度标签。然而,当设置x轴刻度范围时,所有的条形图都压缩到了图形的左侧。

DataFrame示例

  1. 温度 年份
  2. 0 82 1900
  3. 1 52 1901
  4. 2 33 1902
  5. 3 91 1903
  6. 4 44 1904

代码

  1. import pandas as pd
  2. import seaborn as sns
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. # 随机样本数据
  6. np.random.seed(365)
  7. df = pd.DataFrame({'温度': np.random.randint(0, 100, 124), '年份': range(1900, 2024)})
  8. # 根据最小和最大年份设置xticks
  9. sns.barplot(data=df, x='年份', y='温度')
  10. _ = 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

  1. Temperature Year
  2. 0 82 1900
  3. 1 52 1901
  4. 2 33 1902
  5. 3 91 1903
  6. 4 44 1904

Code

  1. import pandas as pd
  2. import seaborn as sns
  3. import numpy as np
  4. import matplotlib.pyplot as plt
  5. # random sample data
  6. np.random.seed(365)
  7. df = pd.DataFrame({'Temperature': np.random.randint(0, 100, 124), 'Year': range(1900, 2024)})
  8. # setting xticks based on the min and max year
  9. sns.barplot(data=df, x='Year', y='Temperature')
  10. _ = 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)

  1. # 根据刻度值为0的索引设置xticks
  2. # 颜色设置为单一颜色,因为husl颜色不包含任何信息
  3. sns.barplot(data=df, x='Year', y='Temperature', color='tab:blue', width=0.3)
  4. _ = plt.xticks(range(0, len(df), 12))

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

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

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

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

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


  • 这同样适用于其他类别绘图:
    • violinplotswarmplotstripplotboxplot和水平barplot
  1. flights = sns.load_dataset('flights')
  2. fig, ax = plt.subplots(2, 3, figsize=(12, 8), sharex=False, sharey=False, tight_layout=True)
  3. ax = ax.flat
  4. sns.violinplot(data=flights, x='year', y='passengers', color='tab:pink', ax=ax[0])
  5. ax[0].set_xticks(range(0, len(df.year.unique()), 2))
  6. sns.swarmplot(data=flights, x='year', y='passengers', size=3, ax=ax[1])
  7. ax[1].set_xticks(range(0, len(df.year.unique()), 2))
  8. sns.stripplot(data=flights, x='year', y='passengers', size=3, ax=ax[2])
  9. ax[2].set_xticks(range(0, len(df.year.unique()), 2))
  10. sns.boxplot(data=flights, x='year', y='passengers', color='tab:pink', ax=ax[3])
  11. ax[3].set_xticks(range(0, len(df.year.unique()), 2))
  12. sns.barplot(data=flights, y='year', x='passengers', color='tab:pink', orient='h', ax=ax[5])
  13. ax[5].set_yticks(range(0, len(df.year.unique()), 2))
  14. ax[4].remove()
  15. 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).
  1. # setting xticks based on the ticks being 0 indexed
  2. # color was set to a single color, because the husl color did not encode any information
  3. sns.barplot(data=df, x='Year', y='Temperature', color='tab:blue', width=0.3)
  4. _ = plt.xticks(range(0, len(df), 12))

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

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

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

  1. plt.bar(height='Temperature', x='Year', data=df)
  2. _ = 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.
  1. flights = sns.load_dataset('flights')
  2. fig, ax = plt.subplots(2, 3, figsize=(12, 8), sharex=False, sharey=False, tight_layout=True)
  3. ax = ax.flat
  4. sns.violinplot(data=flights, x='year', y='passengers', color='tab:pink', ax=ax[0])
  5. ax[0].set_xticks(range(0, len(df.year.unique()), 2))
  6. sns.swarmplot(data=flights, x='year', y='passengers', size=3, ax=ax[1])
  7. ax[1].set_xticks(range(0, len(df.year.unique()), 2))
  8. sns.stripplot(data=flights, x='year', y='passengers', size=3, ax=ax[2])
  9. ax[2].set_xticks(range(0, len(df.year.unique()), 2))
  10. sns.boxplot(data=flights, x='year', y='passengers', color='tab:pink', ax=ax[3])
  11. ax[3].set_xticks(range(0, len(df.year.unique()), 2))
  12. sns.barplot(data=flights, y='year', x='passengers', color='tab:pink', orient='h', ax=ax[5])
  13. ax[5].set_yticks(range(0, len(df.year.unique()), 2))
  14. ax[4].remove()
  15. 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:

确定