【问题标题】:Problem when i do a scatter plot with lot of dates in the x axis当我在 x 轴上有很多日期的散点图时出现问题
【发布时间】:2021-12-20 20:54:25
【问题描述】:

我正在尝试做一个散点图,当我尝试这样做时,x 轴显示了很多日期。有没有办法在散点图中显示的 x 轴上只放置几个日期或年份?

import numpy as np
import pandas as pd

import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
import matplotlib.dates as mdates

plt.scatter(terremoto_sur['time'],terremoto_sur['mag'])
plt.title('Magnitud terremotos en el tiempo zona Sur')
plt.xlabel('Time')
plt.ylabel('Magnitude')
plt.show()

Here is the scatter plot with the problem

【问题讨论】:

  • 你在documentation发现了什么?
  • 看起来 terremoto_sur['time'] 是字符串而不是日期时间。
  • teremoto_sur['time'] 就像这个 1906-08-17T00:40:04.000Z,它是一个字符串。我要将这个巨大的字符串列表更改为数据时间,看看会发生什么。

标签: python pandas matplotlib scatter-plot scatter


【解决方案1】:

如果不查看列的 dtype 就很难判断,但可能发生的情况是“时间”列不是特定于时间的 pandas 数据类型,如 Timestamp 或 DatetimeIndex。例如,如果 'time' 以 object 的 dtype 存储,则每个时间数据点本质上是一个字符串,matplotlib 只是用自己的刻度线绘制每个数据点,字符串在刻度线下方。

您应该检查列的 dtype,如有必要,使用 to_datetime 方法之类的方法转换 dtype。

【讨论】:

  • 是的!我没有看到我的 terremoto_sur['time'] 它是字符串类型而不是数据时间序列。当我改变它时,散点图起作用了。非常感谢
【解决方案2】:

试试这个设置均匀的间距 plt.gca().xaxis.set_major_locator(plt.MultipleLocator(1))

您也可以尝试使用此方法每隔一个刻度采样一次

ax = plt.gca()
ax.set_xticks(ax.get_xticks()[::2])

【讨论】:

  • 问题是我的 x 轴不是数据时间,所以我改变了它,用你的代码我的情节看起来很棒。非常感谢
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-02-07
  • 1970-01-01
  • 1970-01-01
  • 2019-07-09
  • 2022-01-24
相关资源
最近更新 更多