使用Matplotlib可视化CSV数据 [英] Using Matplotlib, visualize CSV data
问题描述
使用matplotlib/熊猫/python,我无法将数据可视化为每30分钟和每天的值是一个新问题,与该问题密切相关.
Using matplotlib/pandas/python, I cannot visualize data as values per 30mins and per days is a new question, which is strongly related to this question.
我想用Matplotlib可视化CSV数据.
I want to visualize CSV data with Matplotlib.
以下是我的代码,名为 1.30mins.py
Following is my code named 1.30mins.py
import matplotlib.pyplot as plt
from matplotlib import style
import numpy as np
style.use('ggplot')
x,y =np.loadtxt('total_watt.csv',
unpack = True,
delimiter = ',')
plt.plot(x,y)
plt.title('Example')
plt.ylabel('Y axis')
plt.xlabel('X axis')
plt.show()
当我故意 1.30mins.py
时,收到以下错误消息.
When I implemtented 1.30mins.py
, I got a following error message.
(DataVizProj)Soma-Suzuki:Soma Suzuki$ python 1.30mins.py
Traceback (most recent call last):
File "1.30mins.py", line 10, in <module>
delimiter = ',')
File "/Users/Suzuki/Envs/DataVizProj/lib/python2.7/site-packages/numpy/lib/npyio.py", line 856, in loadtxt
items = [conv(val) for (conv, val) in zip(converters, vals)]
ValueError: invalid literal for float(): 2011-04-18 13:22:00
这是我的 total_watt.csv
2011-04-18 21:22:00 659.670303375527
2011-04-18 21:52:00 576.304871428571
2011-04-18 22:22:00 2,497.20620579196
2011-04-18 22:52:00 2,790.20392088608
2011-04-18 23:22:00 1,092.20906629318
2011-04-18 23:52:00 825.994417375886
2011-04-19 00:22:00 2,397.16672089666
2011-04-19 00:52:00 1,411.66659265233
据我自己搜索,我需要在程序中添加 converters
或%y-%m-%t
.
As far as I searched by myself, I need to add converters
or, %y-%m-%t
to my program.
我的python版本是2.76我的matpltlib版本是1.42
My python version is 2.76 My matpltlib version is 1.42
推荐答案
您的数据
2011-04-18 21:22:00 659.670303375527
2011-04-18 21:52:00 576.304871428571
...
不受空格或逗号分隔.可以认为它具有固定宽度但是列. np.genfromtxt
可以读取固定宽度的数据.而不是通过字符串到 delimiter
,传递一个表示每个字符串的宽度的整数序列字段.
is not delimited by spaces or commas. It could be regarded as having fixed-width
columns however. np.genfromtxt
can read fixed-width data. Instead of passing a
string to delimiter
, pass a sequence of ints representing the width of each
field.
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
from matplotlib import style
style.use('ggplot')
x, y = np.genfromtxt('total_watt.csv',
unpack=True,
delimiter=[19, 10**6], dtype=None)
x = mdates.datestr2num(x)
y = np.array(np.char.replace(y, ',', ''), dtype=float)
fig, ax = plt.subplots()
ax.plot(x, y)
plt.title('Example')
plt.ylabel('Y axis')
plt.xlabel('X axis')
xfmt = mdates.DateFormatter('%Y-%m-%d %H:%M:%S')
ax.xaxis.set_major_formatter(xfmt)
fig.autofmt_xdate()
plt.show()
产量
这篇关于使用Matplotlib可视化CSV数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!