英文:
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')
示例 1:ax.xaxis.set_major_locator(mdates.DayLocator(interval=3))
示例 2:ax.xaxis.set_major_locator(mdates.MonthLocator(bymonthday=-1))
您可以通过阅读matplotlib.dates
文档来了解更多信息。
<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>
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论