11
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PythonでCSVから折れ線グラフを作る

Last updated at Posted at 2018-07-09

これまではExcelを使ってCSVファイルをグラフ化していましたが、見た目の調整やそもそもセルの範囲が正しく選択されているかを確認するなど、かなり手間がかかっていました。Python(pandas)を使うと簡単にグラフ化できたため、手順をまとめてみました。

GitHub:https://github.com/unhurried/python-csv-to-line-graph

# Generate a fake csv file.

import datetime
import random

file = open("data.csv", "w")

# header
file.write("date,data1,data2\n")

# data
date = datetime.datetime.now()
data1 = 0.5
data2 = 0.5

for i in range(100):
    date = date + datetime.timedelta(seconds=1)
    data1 = data1 + random.uniform(-0.01,0.01)
    data2 = data2 + random.uniform(-0.01,0.01)
    
    file.write(date.strftime("%Y/%m/%d %H:%M:%S"))
    file.write(",")
    file.write(str(data1))
    file.write(",")
    file.write(str(data2))
    file.write("\n")

file.close()
# A function that draws a line graph from a csv file.

%matplotlib inline
import pandas as pd
import matplotlib.pyplot as plt
import os

def draw_line_graph_from_csv(file_name, x_axis, y_axes=None):
    df = pd.read_csv(file_name)
    filter = [x_axis] + y_axes

    title = os.path.basename(file_name)
    df[filter].plot(x=x_axis, title=title, grid=True, rot=10, figsize=(6, 4))
draw_line_graph_from_csv('data.csv', 'date', ['data1'])

[output_3_0.png

draw_line_graph_from_csv('data.csv', 'date', ['data1', 'data2'])

output_4_0.png

11
12
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
12

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?