【问题标题】:Displayed ticks on x-axis in Matplotlib using the bar plot使用条形图在 Matplotlib 中的 x 轴上显示刻度
【发布时间】:2021-06-18 08:33:27
【问题描述】:

我正在尝试使用 pandas 和 matplotlib 绘制直方图数据。我正在使用dataframe.plot() 函数。问题是,这会生成一个在 x 轴上显示大量刻度的图表。 histogram plot

数据框的索引用作刻度。 代码如下:

fig, axes = plt.subplots(figsize=(12,12))

PLOT_CONFIG_HISTOGRAM={
    "subplots":True,
    "title":"cyclictest wakeup latency",
    "legend":True,
    "xlabel":"latency/us",
    "ylabel":"cycles",
    "logy":True,
    "kind":"bar",
}

my_dataframe.plot(ax=axes,**PLOT_CONFIG_HISTOGRAM)

matplotlib 或 pandas 中有没有办法减少显示的刻度?还是显示直方图数据的更好方法?

最后应该是这样的:

| | | | |
|       |
1       5

或者像这样:

|       |
1       5

提前感谢您的任何意见。

【问题讨论】:

    标签: python pandas matplotlib


    【解决方案1】:

    您可以通过在 locator_params 中指定 bin 的数量来设置所需的刻度数:

    plt.locator_params(axis='x', nbins=10)
    

    为了进一步清理你的情节,您还可以旋转 xticks 并设置 xlimits,如下所示:

    plt.xticks(rotation = '90')
    plt.xlim(a,b) #where a and b represent the minimum and maximum of your x values
    

    【讨论】:

      【解决方案2】:

      您可以使用固定数字,例如20,您的情节的垃圾箱:

      PLOT_CONFIG_HISTOGRAM={
          [...]
          "bins": 20,
          [...]
      }
      

      或者,如果您想保持直方图的分辨率,但又想降低 x 轴标签的分辨率,例如仅显示每个 50th 滴答声:

      div = 50
      locs, labels = plt.xticks()
      plt.xticks(locs[::div], labels[::div])
      

      【讨论】:

      • 感谢您到目前为止的帮助。这只会影响我情节的最后一张图。我猜这是因为它是 matplotlib 的“交互方式”而不是“OO 方式”?我怎样才能为每个轴做到这一点?
      • 好吧,我确实设法通过使用get_xticks()get_xticklabels()set_xticks()set_xticklabels() 自己做到了。但我觉得,应该有一种更简单的方法来设置刻度。
      猜你喜欢
      • 2013-03-31
      • 2015-07-21
      • 2020-07-26
      • 1970-01-01
      • 2021-04-03
      • 1970-01-01
      • 2020-05-29
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多