-如何将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,但是它似乎没有任何作用。
答案 0 :(得分:2)
首先,将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)
答案 1 :(得分:0)
根据以上评论,我可以这样解决。
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