【问题标题】:Python, Matplotlib: How to set the axis range when x is time?Python,Matplotlib:当x为时间时如何设置轴范围?
【发布时间】:2020-05-05 08:56:50
【问题描述】:

我正在家里做我学校的 Arduino 项目,老师让我为他可视化我的数据。在我的 x 轴上,我有超过 20K 的时间点需要显示,我尝试为其设置一个范围。

我想要实现的图表:

我到现在为止:

很明显我做错了什么,我已经研究了解决它的方法。

我的绘图部分的#部分是我从互联网上学到的,但它们在这里不起作用。

请帮助我,如果有任何不清楚的地方,请告诉我!

import csv
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
# 1 temperature
# 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)

plt.legend()
plt.show()
plt.savefig('plot.png')

【问题讨论】:

  • 您是否正在寻找使用 r 的解决方案?如果是这样,您能否提供一个可重复的小数据集示例? (在这里查看操作方法:stackoverflow.com/questions/5963269/…
  • 欢迎来到 SO!如果您查看How do I ask and answer homework questions? 并修改您的问题,我认为您可以提高获得答案的机会。
  • 感谢您回复我!我真的很难解释我的想法,因为我是 python 菜鸟和英语学习者!

标签: python r matplotlib range axis


【解决方案1】:

这里有一个示例,说明如何使用 r 绘制数据:

由于您没有提供可重现的示例,因此我使用对您代码的理解创建了一个假的。基本上,看起来您有一个包含 4 列的文件:Days、Temperature、Humidity 和 Light_levels。在这里,我只创建了两列。

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

datafame 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")

希望它能帮助您弄清楚如何绘制数据。

【讨论】:

  • 你好 dc37!哇,这真的是一个非常复杂的r 代码!恐怕我现在无法理解 r,但我非常感谢您的回复!再次感谢您的解释!
  • 不客气!但这并不是一个真正困难的代码,当你进入 R 时,你会发现它实际上很容易。网上有很多教程可以帮助你入门
猜你喜欢
  • 2011-02-20
  • 1970-01-01
  • 2019-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-06
相关资源
最近更新 更多