从csv读取数据并创建图形

时间:2017-09-09 18:10:28

标签: python csv plot graph trend

我有一个csv文件,其中包含以下格式的数据 -

Issue_Type     DateTime
Issue1          03/07/2011 11:20:44
Issue2          01/05/2011 12:30:34
Issue3          01/01/2011 09:44:21
...             ...

我能够阅读此csv文件,但我无法实现的是根据数据绘制图表或趋势图。

例如 - 我试图绘制一个图表,其中X轴为Datetime(仅为月),Y轴为#of Issues。因此,我将在线图中显示趋势,其中3行表示当月每个类别下的问题模式。

我真的没有用于绘制图表的代码,因此无法共享任何代码,但到目前为止我只阅读csv文件。我不确定如何进一步绘制图表

PS:我不是一直在使用python - 因为我之前使用python解析过csv虽然使用了这种语言,但如果使用其他语言有更简单的方法 - 我会打开探索这一点。

3 个答案:

答案 0 :(得分:1)

执行此操作的方法是将数据框与pandas一起使用。

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

df = pd.read_csv("D:\Programmes Python\Data\Data_csv.txt",sep=";")  #Reads the csv
df.index = pd.to_datetime(df["DateTime"]) #Set the index of the dataframe to the DateTime column
del df["DateTime"] #The DateTime column is now useless

fig, ax = plt.subplots()
ax.plot(df.index,df["Issue_Type"])
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m'))  #This will only show the month number on the graph

这假设Issue1 / 2/3是整数,我认为它们是因为我并没有真正理解它们应该是什么。

编辑:这应该可以解决问题,它并不漂亮,可能会进行优化,但效果很好:

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

df = pd.read_csv("D:\Programmes Python\Data\Data_csv.txt",sep=";")
df.index = pd.to_datetime(df["DateTime"])
del df["DateTime"]
list=[]
for Issue in df["Issue_Type"]:
    list.append(int(Issue[5:]))
df["Issue_number"]=list

fig, ax = plt.subplots()
ax.plot(df.index,df["Issue_number"])
ax.xaxis.set_major_formatter(mdates.DateFormatter('%m'))
plt.show()

答案 1 :(得分:0)

您需要做的第一件事是将日期时间字段解析为日期/时间。请尝试使用dateutil.parser

接下来,您需要计算每个月中每种类型的问题数量。这样做的天真方法是维护每个问题类型的列表列表,然后遍历每一列,查看它是哪个月份和哪个问题类型,然后递增相应的计数器。

如果您有问题的频次数,按问题类型排序,您可以根据这样的日期绘制它们:

import matplotlib.pyplot as plt
import datetime as dt

dates = []
for year in range(starting_year, ending_year):
    for month in range(1, 12):
        dates.append(dt.datetime(year=year, month=month, day=1))

formatted_dates = dates.DateFormatter('%b') # Format dates to only show month names
fig = plt.figure()
ax = fig.add_subplot(111)
ax.plot(issues[0], dates) # To plot just issues of type 1
ax.plot(issues[1], dates) # To plot just issues of type 2
ax.plot(issues[2], dates) # To plot just issues of type 3
ax.xaxis.set_major_formatter(formatted_dates) # Format X tick labels
plt.show()
plt.close()

答案 2 :(得分:0)

老实说,我会在下载/设置R& R时使用R. check this link out。 RStudio。

data <- read.csv(file="c:/yourdatafile.csv", header=TRUE, sep=",")
attach(data)
data$Month <- format(as.Date(data$DateTime), "%m")    
plot(DateTime, Issue_Type)