2017-09-16 119 views
1

我想要的X标签是这样的:Python的情节X标签半小时

00:00 00:30 01:00 01:30 02:00 ...... 23:30 

我的代码:

import matplotlib.pyplot as plt 
import pandas as pd 
import matplotlib.dates as mdates 
import random 

data = [random.random() for i in range(48)] 
times = pd.date_range('16-09-2017', periods=48, freq='30MIN') 

fig, ax = plt.subplots(1) 
fig.autofmt_xdate() 
plt.plot(times, data) 

xfmt = mdates.DateFormatter('%H:%M') 
ax.xaxis.set_major_formatter(xfmt) 

plt.show() 

但我的X-标签看起来是这样的:

x-axis image

最新问题? 我有48个值,每个值代表了一天半小时值

+0

多少X-蜱你想要什么?绘制所有48个x值将使x轴标签非常拥挤。 –

+0

可以绘制所有48个值,但绘图的大小需要增加以使其可读。 – StefanK

回答

-1

编辑:为matplotlib和 作为我的答案已经被接受,但不能正常工作,我加了简化的解决方案大熊猫

关键是要设置x-ticks参数正确

在你的情况可能是这样的:

data = [random.random() for i in range(48)] 
times = pd.date_range('16-09-2017', periods=48, freq='30MIN') 

我ñ这两种情况下,你希望只使用小时和分钟:

hour_minutes = times.strftime('%H:%M')

1 Matplotlib解决方案

plt.figure(figsize=(12,5)) 
plt.plot(range(len(data)),data) 
# .plot(times, data) 
plt.xticks(range(len(hour_minutes)), hour_minutes, size='small', 
      rotation=45, horizontalalignment='center') 

plt.show() 

enter image description here

2.熊猫的解决方案

# create dataframe from arrays (not neccessary, but nice) 
df = pd.DataFrame({'values': data, 
         'hour_minutes': hour_minutes}) 

# specify size of plot 
value_plot = df.plot(figsize=(12,5), title='Value by Half-hours') 
# first set number of ticks 
value_plot.set_xticks(df.index) 
# and label them after 
value_plot.set_xticklabels(df.hour_minutes, rotation=45, size='small') 

# get the plot figure and save it 
fig = value_plot.get_figure() 
fig.savefig('value_plot.png') 

enter image description here

但我也一样,在这里提出的另一种方法:)

+0

谢谢。这有效,但看起来很可怕。 :)问题得到解答,我会继续使用其他x-Label –

+0

如果您想让它看起来更漂亮,则需要在保存时提高输出的分辨率。 – StefanK

3

您可以使用MinuteLocator并明确将其设置为每0-30分钟。

minlocator = mdates.MinuteLocator(byminute=[0,30]) 
ax.xaxis.set_major_locator(minlocator) 

而且把它清理干净 - 删除多余的刻度线,并填写空白。

xticks = ax.get_xticks() 
ax.set_xticks(xticks[2:-2]); 
hh = pd.Timedelta('30min') 
ax.set_xlim(times[0] - hh, times[-1] + hh) 

enter image description here

+0

我喜欢你的解决方案,但这里的关键是改变图形大小,所以x轴将是可读的。 – StefanK

+0

它很容易改变图形大小,只需在你的'plt.subplots'中调用。像这样:'fig,ax = plt.subplots(1,figsize =(14,6))' –