【问题标题】:Plotting a data.frame in R在 R 中绘制 data.frame
【发布时间】:2023-03-04 00:24:01
【问题描述】:

我是 R 新手,我需要建议在 R 中绘制一个如下所示的数据框:

         V1          V2         V3          V4         
          1       Mazda     Toyota     Peugeot
   Car1.txt 0,507778837 0,19834711 0,146892655
   Car2.txt 0,908717802 0,64214047 0,396508728

我想绘制这个数据框(实际上有 7 列和 95 行) 在单个图表中,其中 v2、v3、v4 表示一条不同颜色的线,并以汽车名称命名,V1 作为 x 轴的标签,而 y 轴在 [0,1] 范围内。

我真的不知道如何做到这一点,所以我非常感谢任何建议

【问题讨论】:

  • R Introduction了吗?有关于图形的部分。但是对于开始检查导入数据部分,因为它看起来像您的数据没有正确读入 R。欢迎使用 StackOverflow ;)
  • 要开始使用,请查看 R 介绍手册,第 12 章:cran.r-project.org/doc/manuals/R-intro.pdf

标签: r plot dataframe


【解决方案1】:

医生对 Roman 的数据框进行了轻微修改。

library(ggplot2)
my.cars <- data.frame(
  Toyota = runif(50), 
  Mazda = runif(50), 
  Renault = runif(50),
  Car = paste("Car", 1:50, ".txt", sep = "")  
)

my.cars.melted <- melt(my.cars, id.vars = "Car")

然后他建议汽车变量看起来是分类的,所以您的首选是条形图。

p_bar <- ggplot(my.cars.melted, aes(Car, value, fill = variable)) +
  geom_bar(position = "dodge")
p_bar

然后他指出,对于 95 辆汽车,这可能会有点麻烦。也许点图会更合适。

p_dot <- ggplot(my.cars.melted, aes(Car, value, col = variable)) +
  geom_point() +
  opts(axis.text.x = theme_text(angle = 90))
p_dot

由于要从中获取有用信息仍然有点棘手,因此最好按平均值(无论价值意味着什么)订购汽车

my.cars.melted$Car <- with(my.cars.melted, reorder(Car, value))

(然后像以前一样重画p_dot。)

最后,医生说可以画出罗曼推荐的线图

p_lines <- ggplot(my.cars.melted, aes(as.numeric(Car), value, col = variable)) +
  geom_line()
p_lines

【讨论】:

  • melt 需要library(reshape)
【解决方案2】:

这应该让你开始。

my.cars <- data.frame(Toyota = runif(50), Mazda = runif(50), Renault = runif(50)) #make some fake data for this example
plot(x = 1:nrow(my.cars), y = my.cars$Toyota, type = "n") #make an empty plot
with(my.cars, lines(x = 1:nrow(my.cars), y = Toyota, col = "red")) #add lines for Toyota
with(my.cars, lines(x = 1:nrow(my.cars), y = Mazda, col = "red")) # add lines for Mazda
with(my.cars, lines(x = 1:nrow(my.cars), y = Renault, col = "navy blue")) # add lines for Renault

我使用了with(),这样您就不必在每次调用列时都输入my.cars$Toyotamy.cars$Mazda...。探索?par 以获取可以传递给plot 的更多参数。有 ggplot2 解决方案的医生很快就会见到您。

【讨论】:

    【解决方案3】:

    数据框不能像示例中那样构造,所以我稍微修改一下:

    tcars <- read.table(textConnection(" V1       Mazda     Toyota     Peugeot
        Car1.txt 0,507778837 0,19834711 0,146892655
        Car2.txt 0,908717802 0,64214047 0,396508728", header=TRUE, dec=",")
     # need to use dec arg with commas as decimal points!
     tcars
            V1     Mazda    Toyota   Peugeot
    1 Car1.txt 0.5077788 0.1983471 0.1468927
    2 Car2.txt 0.9087178 0.6421405 0.3965087
    
     matplot(data.matrix(tcars[-1]), type="b", xaxt="n")
     axis(1, labels=tcars[[1]],at=1:NROW(tcars))
    

    Resulting plot

    【讨论】:

      猜你喜欢
      • 2019-10-05
      • 1970-01-01
      • 1970-01-01
      • 2016-08-26
      • 2023-04-03
      • 1970-01-01
      • 2020-09-03
      • 2023-03-31
      • 2014-12-27
      相关资源
      最近更新 更多