简体   繁体   中英

How to plot date column as x-axis and data on y axis in Python

I have data of following form in csv file:

date    unepmloyment    inflation
01-01-1948  3.4 2.2
01-02-1948  3.8 2.05
01-03-1948  4   1.5
01-04-1948  3.9 1.82
01-05-1948  3.5 2.06
01-06-1948  3.6 2.07
01-07-1948  3.6 2.17
01-08-1948  3.9 2.03
01-09-1948  3.8 1.52
01-10-1948  3.7 1.4
01-11-1948  3.8 1.1
01-12-1948  4   0.64
01-01-1949  4.3 0.33
01-02-1949  4.7 0.24

I want to plot the date column in x-axis and the other two columns in y-axis corresponding to given date of data.

My Code:

import pandas as pd 
import numpy as np
import matplotlib.pyplot as plt

my_data = pd.read_csv('my_file.csv', index_col = 1) 
array_data = np.array(my_data)
y = array_data[:,2] 
x = array_data[:,0] 
plt.plot(x, y, color='black', linestyle=':', label='something something')    
plt.show()

As I am new to programming can somebody help.

The following should work, using pandas builtin DataFrame.plot() command.

For your data, you may need to tell read_csv that your dates have the day first (default is month first):

import pandas as pd 
import matplotlib.pyplot as plt

my_data = pd.read_csv('my_file.csv',dayfirst=True,index_col=0)
my_data.plot()

plt.show()

在此处输入图片说明

Just try to parse the dates and plot the complete dataframe with pandas:

import pandas as pd 
import matplotlib.pyplot as plt

my_data = pd.read_csv('test.csv',parse_dates=['date'],index_col=['date'],dayfirst=True)

my_data.plot(linestyle=':') 

plt.show()

and for me return:

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM