【问题标题】:R graphic points segmentsR图形点段
【发布时间】:2017-11-27 19:37:51
【问题描述】:

为了在上面绘制点和线段,我必须在 R 中制作一个图形。 我需要在同一个图形上对 W2、W3、W4 做完全相同的事情,但我不知道如何在第一个图形上添加它。对于 W2 x 应该是 2,对于 w3 应该是 3 等等。还有,有人能告诉我怎么可能用 for 来做到这一点,并且还出现在同一个图形中? 我还想以某种方式用虚线绘制一个点及其在轴上的坐标之间的线。

 w1<-c(-0.931,-3.858,3.1946,1.2263)
    w2<-c(-0.1075,-1.4753,-2.4762,1.9593)
    w3<-c(-0.6301,0.7811,1.5725,0.1442)
    w4<-c(0.6267,-1.2948,-0.1932,-0.5225)
    w5<-c(0.1683,-0.2534,0.0937,-0.2469)
    cent<-cbind(w1,w2,w3,w4,w5)
    cent
    comp<-c("W1","W2","W3","W4","W5")
    plot(c(1,1,1,1),y=cent[,1], xlab="Componente",ylab="Centroid",pch=19)
    segments(1,max(cent[,1]),1,min(cent[,1]) )

    library(ggplot2)
    ggplot(centroizi_w, aes(x=c(1,1,1,1), y=cent[,1]))   +
      geom_point()

【问题讨论】:

    标签: r plot ggplot2 graphics


    【解决方案1】:

    您可以使用tidyr 将您的 df 转换为长格式,然后按键分组(即 W 值)...

    library(ggplot2)
    library(tidyr)
    centroizi_w <- gather(as.data.frame(centroizi)) #this converts the matrix to a df, 
                             #then to long format, with default columns 'value' and 'key'
    
    ggplot(centroizi_w, aes(x=as.numeric(as.factor(key)), y=value, group=key))   +
      geom_point()
    

    如果 W 的值超过十个,那么在上面使用 x=as.numeric(gsub("W","",key)) 会更好,因为因子方法将按字母而不是数字排序!

    【讨论】:

      【解决方案2】:

      从这里开始。我很难弄清楚这些段和虚线的用途,所以可能需要做更多的工作。

      library(dplyr)
      centroizi <- as.data.frame(centroizi)
      
      centroizi <- centroizi %>%
        gather(Key, Value) %>%
        mutate(x = as.numeric(substr(Key, 2, 2)))
      
      ggplot(centroizi) + 
       geom_point(aes(x=x, y=Value, colour = Key)) +
       geom_line(aes(x=x, y=Value, colour = Key)) 
      

      【讨论】:

        猜你喜欢
        • 2017-02-12
        • 1970-01-01
        • 1970-01-01
        • 2015-01-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多