首页 > 解决方案 > 在 R 中绘制数据?条形图或饼图

问题描述

嗨,我是 R 新手,并帮助为我的代码创建这样的图表 在此处输入图像描述

所以我必须比较以下 3 个读取命令中的每一个的处理时间“read_csv、read.csv、read.table .. 我将时间添加到 3 个差异变量但不知道如何绘制它以便读取的类型写在 X 轴上,时间写在 Y 轴上.. 我尝试将结果放入数据框或矩阵中,但我没有得到我想要的图表“就像所附的一样.. 下面是我的代码”,没有 ggplot()

library(tidyverse)
setwd("~/Downloads/IntroR/Data")

#read_csv
start.time <- Sys.time()


read_csv("StudyArea.csv", col_names = TRUE)

end.time <- Sys.time()

Read_csvTime = end.time - start.time

#read.csv
start.time <- Sys.time()


read.csv("StudyArea.csv")

end.time <- Sys.time()

Read.csvTime = end.time - start.time

#read.csv
start.time <- Sys.time()


read.table("StudyArea.csv" , header=TRUE, fill=TRUE,quote="", sep=",")

end.time <- Sys.time()

read.tableTime = end.time - start.time

print(paste("the time it took to read a file using read_csv is:", Read_csvTime , "Seconds"))

print(paste("the time it took to read a file using read.csv is:", Read.csvTime , "Seconds"))

print(paste("the time it took to read a file using read.table is:", read.tableTime , "Seconds"))

标签: r

解决方案


在此处输入图像描述

也许这也有帮助。jwarz 解决方案的附加解决方案。

library(tidyverse)

# construct dataframe
Read_csvTime   <- 2.7
Read.csvTime   <- 2.3
read.tableTime <- 2.1
df <- as.data.frame(cbind(Read_csvTime, Read.csvTime, read.tableTime))

# long format for ggplot
df_long <- df %>%
    pivot_longer(cols = Read_csvTime:read.tableTime,
names_to = "func",
values_to = "times")

# ggplot
figure1 <- ggplot(df_long, aes(x = reorder(func, -times), y = times)) + # order bars in desc 
    geom_bar(stat = "identity", fill="seagreen3") +
    labs(title = "Process control",
         subtitle = "(Time)",
         x = "times",
         y = "func") + 
    geom_text(
        aes(label=times),
        nudge_x=0,
        nudge_y=0.2) +
    scale_y_continuous(
        limits = c(0, 5),
        expand = expansion()
    ) 
# figure with theme
figure1 + theme_minimal()


推荐阅读