我正在家里做我的学校Arduino项目,老师请我为他可视化我的数据。在我的X轴上,我需要显示2万多个时间点,因此我尝试为其设置范围。https://i.stack.imgur.com/YCy5Z.png这是我正在尝试实现的图形。
https://i.stack.imgur.com/i3OSc.png和我自己得到的东西。
很明显,我做错了事,并且我已经研究出解决方法。
我的绘图部分的#部分是我从互联网上学到的,但在这里不起作用。
[请帮助我,如果有任何不清楚的地方,请告诉我!
import matplotlib.pyplot as plt
from datetime import datetime
header = []
data = []
path="DATALOG.csv" #CHANGE filename to match file
file = open(path, newline='')
reader=csv.reader(file)
header=next(reader) #This reads the first row and stores the words in header.
data=[row for row in reader] #This reads the rest and store the data in a list
file.close() #closes the file when complete
#This function will print the headings with their index. Helpful when dealing with many columns
def print_header():
for index, column_header in enumerate(header):
print(index, column_header)
#I want the high and low temperatures in New Glasgow for June 2010
#Key headings
#0 = date/time
# 1tepmtature
#2 humidity %
# 3 light level%
days = []
light = []
for row in range (len(data)):
day = data[row][0]
lights = data[row][3]
current_date=datetime.strptime(data[row][0], "%A %H:%M:%S %d/%m/%Y")
light.append(float(lights)) #store the day’s high temp in list
#store the day’s low temp in list
days.append(str(day))
fig = plt.figure(dpi=128, figsize = (50, 6))
#x = [dc[0] for dc in days]
#xticks = range(0,len(x),10)
#xlabels=[x[index] for index in xticks]
#xticks.append(len(x))
#xlabels.append(days[-1][0])
#ax.set_xticks(xtick)
#ax.set_xticklabels(xlabels,rotation=40)
plt.plot(days,light,c = 'red',label = 'temprature')
plt.title("LIGHT")
plt.xlabel('days',fontsize = 5)
#ax.plot(np.arange('Wednesday 12:00:00 08/01/2020',' Thursday 11:58:10 09/01/2020'), range(10))
fig.autofmt_xdate()
plt.ylabel('light (%)', fontsize = 12)
plt.tick_params(axis='both', which='major', labelsize = 10)
#tick_spacing =
plt.legend()
plt.show()
plt.savefig('plot.png')```
这里是如何使用r
绘制数据的示例:
由于您没有提供可复制的示例,因此我根据对您的代码的了解创建了一个伪造的示例。基本上,看起来您有一个包含4列的文件:天数,温度,湿度和光水平。在这里,我仅创建两列。
set.seed(123)
df <- data.frame(Day = as.character(seq.Date(from = as.Date("2019-01-01", format = "%Y-%m-%d"), to =as.Date("2019-02-01", format = "%Y-%m-%d"), by = "days" )),
Light_levels = sample(0:100,32, replace = TRUE))
数据名人堂df
应该看起来像:
> head(df)
Day Light_levels
1 2019-01-01 30
2 2019-01-02 78
3 2019-01-03 50
4 2019-01-04 13
5 2019-01-05 66
6 2019-01-06 41
我认为您的问题来自日期格式的管理。在r
中,将csv文件作为数据框导入时,它会以因子或字符格式转换日期。
您可以使用str
功能通过查看数据帧的结构进行检查:
> str(df) 'data.frame': 32 obs. of 2 variables: $ Day : Factor w/ 32 levels "2019-01-01","2019-01-02",..: 1 2 3 4 5 6 7 8 9 10 ... $ Light_levels: int 30 78 50 13 66 41 49 42 100 13 ...
因此,要以日期格式使用日期,您需要使用以下方法将此因子格式转换为日期格式:
df$Day = as.Date(df$Day, format = "%Y-%m-%d")
现在,如果您检查
df
的结构,您将看到:
str(df) 'data.frame': 32 obs. of 2 variables: $ Day : Date, format: "2019-01-01" "2019-01-02" "2019-01-03" ... $ Light_levels: int 30 78 50 13 66 41 49 42 100 13 ...
现在,您可以使用软件包
ggplot2
进行打印(首先要安装ggplot2
:]
library(ggplot2)
ggplot(df, aes(x = Day, y = Light_levels))+
geom_line()+
scale_x_date(date_breaks = "days", date_labels = "%b %d")+
theme(axis.text.x = element_text(angle = 45, hjust = 1))
您可以通过使用scale_x_date
的参数来调整每个日期的显示(在此处查看更多信息:https://ggplot2.tidyverse.org/reference/scale_date.html)
或者,无需安装ggplot2
软件包,您可以使用base
R plot
函数来进行安装:
plot(x = df$Day, y = df$Light_levels, type = "l", xaxt = "n", xlab = "")
axis.Date(1,at=seq(min(df$Day), max(df$Day), by="days"), format="%b %d")
希望它将帮助您弄清楚如何绘制数据。