【问题标题】:Seaborn stripplot of datetime objects not working日期时间对象的Seaborn条形图不起作用
【发布时间】:2017-08-06 10:29:04
【问题描述】:

按照 URL 中的第一个示例: http://seaborn.pydata.org/tutorial/categorical.html 我能够加载名为“tips”的数据集并重现显示的带状图。但是,当应用于由 datetime 对象组成的我的 pandas 数据框(称为 df)时,不会显示此图。我的 df 由 19300 行和 7 列组成,其中 2 列是日期时间对象的形式(分别是日期和时间)。我想使用 Python Seaborn 包的 stripplot 函数将这两个 df 列可视化在一起。我的代码如下:

sns.stripplot(x=df['DATE'], y=df['TIME'], data=df);

输出错误如下:

TypeError: float() argument must be a string or a number

在应用绘图命令之前,我已确保从数据列中删除标题。 其他失败的尝试包括(但不限于)

sns.stripplot(x=df['DATE'], y=df['TIME']);

我猜这个错误可能是由于列数据类型的 datetype 对象性质,并且这种类型必须以某种方式更改为字符串或整数值。它是否正确?以及如何继续完成这项任务?

为了说明 df 数据,这是一个使用 matplotlib.pyplot (as plt) 的工作代码

 ax1.plot(x, y, 'o', label='Events') 

非常感谢任何帮助。

【问题讨论】:

标签: python datetime matplotlib plot seaborn


【解决方案1】:

您只需将变量名称作为 x 和 y 的输入;而不是数据本身。例如:

sns.stripplot(x="value", y="measurement", hue="species",
              data=iris, dodge=True, alpha=.25, zorder=1)

https://seaborn.pydata.org/examples/jitter_stripplot.html

【讨论】:

  • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接答案可能会失效。 - From Review
【解决方案2】:

将以下代码应用于之前的脚本后:

x = df['DATE']
data = df['TIME']
y = data[1:len(x)]
x = x[1:len(x)]

s = []
for time in y:
    a = int(str(time).replace(':',''))
    s.append(a)

k = []
for date in x:
    a = str(date)
    k.append(a)

x = k 
y = s

stripplot 工作:

sns.stripplot(x, y)

【讨论】:

    【解决方案3】:

    也可以尝试将日期/时间转换为秒以将它们绘制为数值:

    dates = df.DATE
    times = df.TIME
    
    start_date = dates.min()
    dates_as_seconds = dates.map(lambda d: (d - start_date).total_seconds())
    times_as_seconds = times.map(lambda t: t.second + t.minute*60 + t.hour*3600)
    ax = sns.stripplot(x=dates_as_seconds, y=times_as_seconds)
    ax.set_xticklabels(dates)
    ax.set_yticklabels(times)
    

    当然,数据框应该按日期和时间排序以匹配刻度和值。

    【讨论】:

    • 不错的策略!谢谢。我的长期想法是创建带有日期时间与整数的时间序列图(某些东西的特定测量值)。在绘制时间序列之前,您的建议也可能在将数据组合成等距的日期时间间隔时变得很方便..
    猜你喜欢
    • 1970-01-01
    • 2021-09-19
    • 2014-06-27
    • 2020-11-20
    • 2020-04-29
    • 2016-12-05
    • 2016-12-03
    • 2014-09-27
    • 2020-07-08
    相关资源
    最近更新 更多