在Python绘图中显示日期范围

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

show date in ranges in python plot graph

问题

我已经使用以下代码在Python中绘制了一个数据的图表,这是数据:

{'2022-01-30': 50, '2022-01-31': 152, '2022-02-01': 41, '2022-02-02': 50, '2022-02-03': 50, '2022-02-04': 50, '2022-02-05': 50, '2022-02-06': 50, '2022-02-07': 50, '2022-02-08': 50, '2022-02-09': 50, ......., '2022-09-30': 50, }

我使用以下代码创建了该图表:

df = pd.Series(data, name='Quantity').rename_axis('Date').reset_index()
df.plot(kind='scatter', x='Date', y='Quantity')
plt.show()

但是,图表中的日期都被挤在一点上,而不是以我期望的方式显示日期范围,比如2022-01-30、2022-02-28等,或者2022-01-30、2022-03-31等。请问我如何实现这个目标?

英文:

I have plotted a graph of a data in python using the following code, this is the data

{'2022-01-30': 50, '2022-01-31': 152, '2022-02-01': 41, '2022-02-02': 50,'2022-02-03': 50, '2022-02-04': 50,
'2022-02-05': 50, '2022-02-06': 50, '2022-02-07': 50, '2022-02-08': 50, '2022-02-09': 50, ......., '2022-09-30': 50, }

df = pd.Series(data, name='Quantity').rename_axis('Date').reset_index()
df.plot(kind='scatter', x='Date', y='Quantity')
plt.show()

and it gave me the graph but the days which I expected to be in range are all squashed to the point that it was not visible

I expected the date to come out in ranges like 2022-01-30, 2022-02-28, etc or 2022-01-30, 2022-03-31 etc

Please how can i achieve that

答案1

得分: 1

import matplotlib.dates as mdates

ax = df.plot(kind='scatter', x='Date', y='Quantity')

示例 1ax.xaxis.set_major_locator(mdates.DayLocator(interval=3))

示例 2ax.xaxis.set_major_locator(mdates.MonthLocator(bymonthday=-1))

您可以通过阅读matplotlib.dates文档来了解更多信息。

在Python绘图中显示日期范围
在Python绘图中显示日期范围


<details>
<summary>英文:</summary>

You have multiple possibilities:

import matplotlib.dates as mdates

ax = df.plot(kind='scatter', x='Date', y='Quantity')


**Example 1**: `ax.xaxis.set_major_locator(mdates.DayLocator(interval=3))`

[![enter image description here][1]][1]

**Example 2**: `ax.xaxis.set_major_locator(mdates.MonthLocator(bymonthday=-1))`

[![enter image description here][2]][2]

You can know more by reading the [`matplotlib.dates`][3] documentation.


  [1]: https://i.stack.imgur.com/BSgvs.png
  [2]: https://i.stack.imgur.com/CXieY.png
  [3]: https://matplotlib.org/stable/api/dates_api.html

</details>



huangapple
  • 本文由 发表于 2023年3月8日 19:20:35
  • 转载请务必保留本文链接:https://go.coder-hub.com/75672358.html
匿名

发表评论

匿名网友

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

确定