在 matplotlib 中绘制一个散点图,x 轴为日期,y 轴为值

Make a Scatter Plot in matplotlib with dates on x axis and values on y

我无法制作包含日期数组和一堆 PM 2.5 值的散点图。我的列表如下所示:

dates = ['2015-12-20','2015-09-12']  
PM_25 = [80, 55]
import pandas as pd
dates = ['2015-12-20','2015-09-12']  
PM_25 = [80, 55]
dates = [pd.to_datetime(d) for d in dates]

plt.scatter(dates, PM_25, s =100, c = 'red')

s 设置大小 c 设置颜色

还有一大堆其他参数: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter

如果绘图的数据包含日期,您可以使用plot_date

Similar to the plot() command, except the x or y (or both) data is considered to be dates, and the axis is labeled.

首先将列表转换为日期时间,如@RSHARP 所示,

dates = [pd.to_datetime(d) for d in dates]

那么你可以使用plot_date

plt.plot_date(dates, PM_25, c = 'red')

a pandas dataframe 通常更常见。所以对我来说很有效:

import pandas as pd
dates = ['2015-12-20','2015-09-12']  
PM_25 = [80, 55]
data = pd.DataFrame({'dates':pd.to_datetime(dates),'PM_25':PM_25})
data.plot(x='dates',y='PM_25',marker='o',linestyle='none')

你可以这样定义更多:

data.plot(x='dates',y='PM_25',marker='o',linestyle='none',color='red',ms=3)