Python - 在matplotlib

时间:2018-06-04 15:05:09

标签: python pandas matplotlib

我需要用基本线图绘制一些数据。

       datatime             col1
29/08/2017 10:13:23.972      NaN
29/08/2017 10:13:23.972      NaN
29/08/2017 10:13:54.449      425
29/08/2017 10:14:19.800      425
29/08/2017 10:14:45.232      425
29/08/2017 10:14:48.567      NaN
29/08/2017 10:15:19.331      2
29/08/2017 10:15:38.081      380
29/08/2017 10:16:27.517      380

现在我遇到了一些问题。 我需要的是绘制这个以及是否有NaN在图表上创建一个空格,而不是从前一个到下一个值的行。 我以前用matplotlib绘图但不知道如何整合“跳过”步骤。如果可以在每次跳跃的高低或更低的情况下在线绘制值,那将是很好的。

我有什么:

def plot_1(data, par_time, par_y, par_ylabel, par_legend):
    fig = plt.figure(figsize=(5, 3))
    ax1 = fig.add_subplot(111)
    plt.gca().set_color_cycle(['red', 'blue', 'green', 'brown'])
    ax1.plot(data[par_time], data[par_y], label=par_ylabel, marker='o', linewidth=2.0)
    plt.ylabel(par_ylabel)
    handles, labels = ax1.get_legend_handles_labels()
    ax1.legend(handles, par_legend, loc='upper center', bbox_to_anchor=(1.15, 1))
    ax1.grid('on')
    for i, j in zip(data[par_time], data[par_yticks]):
        ax1.annotate(str(j), xy=(i, j))
    a = plt.savefig('/home/user/graph.png)
    return a

这里没有那么多行,但如果是,x会如此拥挤,是否可以在3秒内创建每个网格?

提前感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

IIUC,此代码可能适合您。我将x轴间隔设置为30秒(而不是3,这是你要求的),因为3秒的间隔会导致x轴的大量拥挤。无论如何,它应该让你知道如何前进。

此代码中创建具有NaN值的差距的基本思路是在数据中创建新列,以便将每个连续(非NaN)块组合在一起,然后绘制这些组中的每一个。

import matplotlib.pyplot as plt
import matplotlib.dates as md

# Make sure `datatime` is in datetime format
df['datatime'] = pd.to_datetime(df.datatime)

# create new group if interrupted by NaN
df['group'] = df.col1.isnull().cumsum()


fig, ax = plt.subplots()
# Groupby your new group column, and plot each group
for _, group in df.groupby('group'):
    plt.plot(group.dropna(subset=['col1']).datatime,
             group.dropna(subset=['col1']).col1,
             color='blue')

# Create your 30 second interval on the x axis, and format your dates
xlocator = md.SecondLocator(interval=30)
dateFmt = md.DateFormatter('%H:%M:%S') 

ax.xaxis.set_major_locator(xlocator)
ax.xaxis.set_major_formatter(dateFmt)
plt.xticks(rotation=90)

enter image description here