Python 在 matplotlib 中制作散点图,x 轴上有日期,y 上有值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/38256750/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 20:34:44  来源:igfitidea点击:

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

pythonlistmatplotlibstatisticsscatter

提问by Ravmcgav

I am having trouble making a scatter plot that has from a date array and a bunch of PM 2.5 values. My lists would look like the following:

我在制作包含日期数组和一堆 PM 2.5 值的散点图时遇到问题。我的列表如下所示:

dates = ['2015-12-20','2015-09-12']  
PM_25 = [80, 55]

回答by RSHAP

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')

ssets the size csets the color

s设置大小 c设置颜色

There are a whole bunch of other args as well: http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.scatter

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

回答by Memin

If a plot with data that contains dates, you can use plot_date

如果绘图的数据包含日期,则可以使用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.

类似于 plot() 命令,除了 x 或 y(或两者)数据被视为日期,并且轴被标记。

First convert list to date time, as @RSHARP showed,

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

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

then you can use plot_date

那么你可以使用 plot_date

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

回答by Anthony

a pandas dataframe is more common usually. so it's efficient to me:

熊猫数据框通常更常见。所以对我来说很有效:

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')

and you can define more like this:

你可以定义更多这样的:

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