【问题标题】:ggplot polygon X- and Y- axis scaling and change color of groupsggplot 多边形 X 轴和 Y 轴缩放并更改组的颜色
【发布时间】:2019-02-17 18:10:48
【问题描述】:

-如何将 Y 轴和 X 轴分别缩放到 0,30 和 0,50 并根据比例绘制数据点?

-如何将第 1、2 和 3 组的颜色更改为紫色、橙色和黄色?

 library(ggplot2)
 library(plotly)

ID <- c("Group 1", "Group 1", "Group 1", "Group 2", "Group 2", "Group 2", "Group 3", "Group 3", "Group 3", "Group 4", "Group 4", "Group 4")
area <- c("Area 1", "Area 1", "Area 1","Area 2", "Area 2", "Area 2", "Area 3", "Area 3", "Area 3", "Area 4", "Area 4", "Area 4")
x <- c(1.0, 10.25, 50.0, 2.0, 5.0, 30.0, 5.0, 9.0, 10.0, 11.0, 23.0, 40.0) 
y <- c(1.0, 3.0, 5.0, 20.0, 10.0, 23.0, 25.0, 19.1, 5.0, 15.0, 8.0, 4.0)

df <- cbind(ID, area, x, y)
df <- as.data.frame(df)
df

p <- ggplot(df, aes(x=x, y=y)) + geom_polygon(aes(fill=factor(ID), group=area))

p <- ggplotly(p)
p

我尝试过使用 scale_x_continuous、scale_fill_manual 和 scale_fill_identity,但它似乎没有任何作用。

【问题讨论】:

  • 你能显示你试过的代码吗?顺便说一句,使用df &lt;- data.frame(ID, area, x, y, stringsAsFactors = FALSE) 创建您的数据,而不是首先使用cbind。这为您省去了一些麻烦(例如,查看轴的标签)。
  • 正如@markus 所说,由于使用cbind,您遇到了问题,它正在创建一个所有值都具有相同类型的矩阵。在这种情况下,该类型是字符,但您可能希望将这些 xy 值视为数值,而不是字符。如果您切换到 markus 的建议,您将有更好的时间使用这些 scale_* 函数。

标签: r ggplot2 polygon r-plotly ggplotly


【解决方案1】:

首先,将 x 和 y 列转换为数字(它们是数据中的因子)。然后,使用 scale_x_continuous 和 scale_y_continuous 设置比例限制。最后,使用 scale_fill_manual 改变颜色(因为你有第四组,我给了它另一种颜色)。

library(tidyverse)
df <- df %>% mutate(x = parse_number(x),
                        y = parse_number(y))

p <- ggplot(df, aes(x=x, y=y)) + geom_polygon(aes(fill=factor(ID), group=area)) + 
    scale_x_continuous(limits = c(0,50)) + 
    scale_y_continuous(limits = c(0,30)) + 
    scale_fill_manual(values = c("purple", "orange", "yellow", "gray40"))
ggplotly(p)

【讨论】:

    【解决方案2】:

    从上面的 cmets 我可以这样解决它。

    library(ggplot2)
    library(plotly)
    
    ID <- c("Group 1", "Group 1", "Group 1", "Group 2", "Group 2", "Group 2", "Group 3", "Group 3", "Group 3", "Group 1", "Group 1", "Group 1")
    area <- c("Area 1", "Area 1", "Area 1","Area 2", "Area 2", "Area 2", "Area 3", "Area 3", "Area 3", "Area 4", "Area 4", "Area 4")
    colours <- c("Purple", "Purple", "Purple", "Green", "Green", "Green", "yellow", "yellow", "yellow", "Purple", "Purple", "Purple")
    x <- c(1.0, 10.25, 50.0, 2.0, 5.0, 30.0, 5.0, 9.0, 10.0, 11.0, 23.0, 40.0) 
    y <- c(1.0, 3.0, 5.0, 20.0, 10.0, 23.0, 25.0, 19.1, 5.0, 15.0, 8.0, 4.0)
    
    df <- data.frame(ID, area, colours, x, y, stringsAsFactors = FALSE )
    
    ###Get colours
    colours_poly <- setNames(df$colours, df$ID)
    colours_poly
    
    p <- ggplot(df, aes(x=x, y=y)) + geom_polygon(aes(fill=factor(ID), group=area)) + 
         scale_x_continuous(limits = c(0,50)) + 
     scale_y_continuous(limits = c(0,30)) +
     scale_fill_manual(values = colours_poly)
    
    
    p <- ggplotly(p)
    p
    

    非常感谢!

    【讨论】: