如何使用python在matplotlib中更改x轴值的日期时间格式? [英] How can I change datetime format of x-axis values in matplotlib using python?

查看:946
本文介绍了如何使用python在matplotlib中更改x轴值的日期时间格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使该图的x轴看起来更好?

How can I make this plot's x-axis looks better?

在绘制数据框中的所有值时,有什么方法可以在x轴上仅显示3个值吗?

Is there any way to show only 3 values in x-axis while plotting all values in my dataframe?

我尝试使用plt.xticks(rotation=70),但是它仍然会减少我的电话号码.

I tried using plt.xticks(rotation=70) but it still cuts my numbers..

如您所见,它以MMM DD YYYY格式显示日期.

As you can see, it shows the date in the format MMM DD YYYY.

我想要类似MMM DDDD MMM的名称.甚至用2写 第DD MM \n YYYY行.

I wanna something like MMM DD or DD MMM. Or even writing in 2 lines DD MM \n YYYY.

我该如何实现?

这是用于生成图表的代码:

This is the code used for generating the chart:

plt.plot(df_21d["Timestamp"], df_21d["Close"], label="Price", color="b")    

plt.title("BTC - 21 Dias")

plt.xlabel("Data")
plt.ylabel("Preco (em USD)")

plt.grid(True)

plt.show()

这是我的数据:

df_21d ["Timestamp"]

667   2016-05-27 08:00:00
668   2016-05-27 08:30:00
669   2016-05-27 09:00:00
670   2016-05-27 09:30:00
671   2016-05-27 10:00:00
Name: Timestamp, dtype: datetime64[ns]

df_21d [关闭"]

667    480.00
668    471.36
669    477.35
670    476.55
671    479.92
Name: Close, dtype: float64

我不知道是否必须格式化df_21d.Timestamp或它是否是matplotlib配置.也许使用plt.xticks()格式化时间戳并将其作为矢量传递...但是我不确定该怎么做...

I dont know if I have to format df_21d.Timestamp or if it's a matplotlib configuration. Maybe formatting the timestamp and passing it as a vector using plt.xticks()... but I'm not sure about how do that...

或者甚至可以只插入x轴的第一个,最后一个和中间值,例如:

Or maybe even inserting only the first, the last and the middle value for the x-axis, with something like:

plt.xaxis_labels = (df_21d["Timestamp"][1], 
             df_21d["Timestamp"][len(df_21d["Timestamp"])/2], 
             df_21d["Timestamp"][len(df_21d["Timestamp"])])

推荐答案

此答案可能会帮助您: 不写出Matplotlib轴上的所有日期

This answer might help you: Not write out all dates on an axis, Matplotlib

基本上,您可以通过设置日期格式来设置日期格式:

Essentially, you can set the format of dates by setting the format:

plt.gca().xaxis.set_major_formatter(mdates.DateFormatter('%d %m'))

这篇关于如何使用python在matplotlib中更改x轴值的日期时间格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆