我们如何在python中绘制时间散点图

时间:2020-06-05 04:52:54

标签: python pandas time seaborn scatter-plot

我想在提到的两列k和s之间绘制散点图。 k应该在x轴上显示每小时24小时的时间,而s应该在y轴上显示。我已经使用sns.relplot尝试了一些代码,但是出现了属性错误。

data columns in which we want scatter plot

code which we tried with error

1 个答案:

答案 0 :(得分:0)

尝试:

import matplotlib.dates as mdates
from datetime import time
import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame([['2020-05-26 06:15:07','105'], ['2020-05-26 06:15:07','41'], ['2020-05-26 06:16:51','95']], columns=["k", "s"]) 
df.k = pd.to_datetime(df.k, format='%Y-%m-%d %H:%M:%S')
ax = sns.scatterplot(df.k, df.s)
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d %H:%M:%S"))
ax.tick_params(axis="x", rotation=45)
ax.plot()

enter image description here


import matplotlib.dates as mdates
from datetime import time
import matplotlib.pyplot as plt
df = pd.DataFrame([['2020-05-26 06:15:07','105'], ['2020-05-26 06:15:07','41'], ['2020-05-26 06:16:51','95']], columns=["k", "s"]) 
df.k = pd.to_datetime(df.k, format='%Y-%m-%d %H:%M:%S')

df.set_index(['k'],inplace=True)
ax = sns.scatterplot(df.index, df.s)
# ax.set(xlabel="time", ylabel="values")
ax.set_xlim(df.index[0], df.index[-1])
ax.xaxis.set_major_locator(mdates.HourLocator())
ax.xaxis.set_major_formatter(mdates.DateFormatter("%Y-%m-%d %H:%M:%S"))
ax.tick_params(axis="x", rotation=45)
ax.plot()

enter image description here