【问题标题】:unable to get the details on the x-axis using plot method in pandas无法使用 pandas 中的绘图方法获取 x 轴上的详细信息
【发布时间】:2018-12-12 00:36:11
【问题描述】:
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 轴下方写了“结束日期”,但我希望提及结束日期列内的所有日期。

【问题讨论】:

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


    【解决方案1】:

    您需要更改 End Date 的 dtype,poll_df 中的 End Date 是一个字符串,将其转换为 datetime dtype 可以让 pandas plot 使用标签正确格式化 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'])
    

    【讨论】:

    • 感谢您的回复,它起作用了。但是 parse_dates 在这里做什么?
    • Per Docs 它在该列上调用 pd.to_datetime。
    猜你喜欢
    • 1970-01-01
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 2019-02-18
    • 2021-04-12
    • 2016-07-11
    • 2017-09-24
    • 1970-01-01
    相关资源
    最近更新 更多