无法通过熊猫中的绘图方法获得x轴的详细信息

时间:2018-07-03 16:06:28

标签: python-3.x pandas numpy dataframe data-science

import pandas as pd
from pandas import Series,DataFrame
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('whitegrid')
%matplotlib inline
poll_df=pd.read_csv('http://elections.huffingtonpost.com/pollster/2012-general-election-romney-vs-obama.csv')
poll_df.plot(x='End Date',y=['Obama','Romney','Undecided'],linestyle='',marker='o')

我在x轴下方仅写了“结束日期”,但我希望提及“结束日期”列中的所有日期。

1 个答案:

答案 0 :(得分:0)

您需要更改“结束日期”的dtype,在poll_df中的“结束日期”是一个字符串,将其转换为datetime dtype可使熊猫图以标签正确格式化x轴:

import pandas as pd
from pandas import Series,DataFrame
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('whitegrid')
%matplotlib inline
poll_df=pd.read_csv('http://elections.huffingtonpost.com/pollster/2012-general-election-romney-vs-obama.csv')
poll_df['End Date'] = pd.to_datetime(poll_df['End Date'])
poll_df.plot(x='End Date',y=['Obama','Romney','Undecided'],linestyle='',marker='o')

输出:

enter image description here

或者您可以在read_csv中使用parse_dates参数:

poll_df=pd.read_csv('http://elections.huffingtonpost.com/pollster/2012-general-election-romney-vs-obama.csv', 
                     parse_dates=['End Date'])