简体   繁体   English

如何在Python中将日期列绘制为x轴并在y轴上绘制数据

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

I have data of following form in csv file: 我在csv文件中有以下格式的数据:

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. 我想在x轴上绘制日期列,在y轴上绘制其他两列,分别对应于给定的数据日期。

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. 以下应工作,利用pandas内置DataFrame.plot()命令。

For your data, you may need to tell read_csv that your dates have the day first (default is month first): 对于您的数据,您可能需要告诉read_csv您的日期以日期为第一(默认是月初):

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: 对我来说:

在此处输入图片说明

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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