无法使用 pandas 中的 plot 方法获取 x 轴上的详细信息
unable to get the details on the x-axis using plot method in pandas
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')
我只 'End Date' 写在 x 轴下方,但我希望提及结束日期列中的所有日期。
您需要更改结束日期的数据类型,poll_df 中的结束日期是一个字符串,将其转换为日期时间数据类型允许 pandas 绘图使用标签正确格式化 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')
输出:
或者您可以在 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'])
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')
我只 'End Date' 写在 x 轴下方,但我希望提及结束日期列中的所有日期。
您需要更改结束日期的数据类型,poll_df 中的结束日期是一个字符串,将其转换为日期时间数据类型允许 pandas 绘图使用标签正确格式化 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')
输出:
或者您可以在 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'])