简体   繁体   English

如何使用python更改matplotlib中x轴值的日期时间格式?

[英]How can I change datetime format of x-axis values in matplotlib using python?

How can I make this plot's x-axis looks better? 如何使这个图的x轴看起来更好?

Is there any way to show only 3 values in x-axis while plotting all values in my dataframe? 在绘制数据框中的所有值时,有没有办法在x轴上只显示3个值?

图片

I tried using plt.xticks(rotation=70) but it still cuts my numbers.. 我尝试使用plt.xticks(rotation=70)但它仍然削减了我的数字..

As you can see, it shows the date in the format MMM DD YYYY . 如您所见,它以MMM DD YYYY格式显示日期。

I wanna something like MMM DD or DD MMM . 我想要像MMM DDDD MMM这样的东西。 Or even writing in 2 lines DD MM \\n YYYY . 甚至可以写成2行DD MM \\n YYYY

How can I achieve that? 我怎样才能做到这一点?

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()

Here's my data: 这是我的数据:

df_21d["Timestamp"] df_21d [ “时间戳”]

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["Close"] df_21d [ “关闭”]

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

I dont know if I have to format df_21d.Timestamp or if it's a matplotlib configuration. 我不知道是否必须格式化df_21d.Timestamp或者它是否是matplotlib配置。 Maybe formatting the timestamp and passing it as a vector using plt.xticks() ... but I'm not sure about how do that... 也许格式化时间戳并使用plt.xticks()将其作为向量传递...但我不确定这是怎么做的...

Or maybe even inserting only the first, the last and the middle value for the x-axis, with something like: 或者甚至可能只插入x轴的第一个,最后一个和中间值,例如:

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

This answer might help you: Not write out all dates on an axis, Matplotlib 这个答案可能对你有所帮助: 不写出轴上的所有日期,Matplotlib

Essentially, you can set the format of dates by setting the format: 基本上,您可以通过设置格式来设置日期的格式:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM