使用pylab绘制图形

时间:2017-06-27 10:01:26

标签: python-2.7 matplotlib

我正在尝试绘制图表。它有一个包含动作名称(文本)的列表和另一个包含动作频率(int)的列表。

我想绘制连接图。这是我写的代码:

xTicks=np.array(action) 
x=np.array(count)
y=np.array(freq)
pl.xticks(x,xTicks)
pl.xticks(rotation=90)
pl.plot(x,y)
pl.show()

在列表xTicks中,我有动作,在列表y中,我有自己的频率。

通过上面的代码,我得到了这张图:

enter image description here

为什么我在x轴上获得额外的空格?它应该是对称的,列表的大小是130-135所以我该如何滚动它?

1 个答案:

答案 0 :(得分:1)

您需要将x设置为均匀间隔的列表,以使x刻度均匀分布。以下是一些包含一些组成数据的示例:

import matplotlib.pyplot as plt
import numpy as np

action = ["test1", "test2", "test3", "test4", "test5", "test6", "test7", "test8", "test9"]
freq = [5,3,7,4,8,3,5,1,12]

y=np.array(freq)
xTicks=np.array(action)

x = np.arange(0,len(action),1) # evenly spaced list with the same length as "freq"

plt.plot(x,y)
plt.xticks(x, xTicks, rotation=90)
plt.show()

这会产生以下情节:

enter image description here

<强>更新

滑块的简单示例如下所示。您必须对此进行更改才能获得您想要的结果,但这将是一个开始:

from matplotlib.widgets import Slider

freq = [5,3,7,4,8,3,5,1,12,5,3,7,4,8,3,5,1,12,5,3,7,4,8,3,5,1,12,4,9,1]

y=np.array(freq)
x = np.arange(0,len(freq),1) # evenly spaced list with the same length as "action"

fig, ax = plt.subplots()
plt.subplots_adjust(left=0.25, bottom=0.25)
l, = plt.plot(x, y, lw=2, color='red')

axfreq = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor="lightblue")
sfreq = Slider(axfreq, 'Slider', 0.1, 10, valinit=3)

def update(val):
    l.set_xdata(val* x)
    fig.canvas.draw_idle()

sfreq.on_changed(update)

plt.show()

这会产生下图,其中有一个滑块:

enter image description here