按类别独立着色点和按ggplot中的高度绘制轮廓

时间:2018-01-24 14:57:02

标签: r ggplot2 colors

以下示例或R代码显示轮廓水平和用于生成轮廓的数据点。

n <- 10

x <- c(rnorm(n,-1,0.5), rnorm(n,1,0.5))
y <- c(rnorm(n,-1,1), rnorm(n,1,0.5))

df <- data.frame(x,y)

# categorise the points
df$cat <- sample(c(1,2), n, replace=T)

library(ggplot2)
p <- ggplot(df)

# for manual colouring of points, but not showing contours due to error
#p <- p + geom_point(aes(x=x,y=y,col=factor(cat)))
#cols <- c("1"="red", "2"="blue")
#p <- p + scale_color_manual(values=cols)

# this works fine except I am not controlling the colours
p <- p + geom_point(aes(x=x,y=y,col=cat))
p <- p + geom_density2d(aes(x=x,y=y,color=..level..))

print(p)

如果我不显示轮廓,我可以根据它们的二进制类别(参见上面注释掉的代码)对点进行着色,但是添加轮廓会产生一个&#34;连续值提供给离散比例&#34 ;错误。

各种尝试都失败了。

问题:是否可以为点(根据类别)着色并独立地为轮廓水平着色(根据高度)?

1 个答案:

答案 0 :(得分:1)

你可以尝试

library(tidyverse)
df %>% 
   ggplot(aes(x=x,y=y)) +
   stat_density_2d(aes(fill = ..level..), geom = "polygon") +
   geom_point(aes(color=factor(cat)), size=5) +
   theme_bw()

enter image description here

或切换到填充工作的点,如shape=21

df %>% 
   ggplot(aes(x=x,y=y)) +
   geom_density2d(aes(color=..level..))+
   geom_point(aes(fill=factor(cat)),color="black",shape=21, size=5) +
   theme_bw() + 
   scale_fill_manual(values = c(2,4)) + 
   scale_color_continuous(low = "green", high = "orange")

或尝试添加scale_color_gradientn(colours = rainbow(10))

enter image description here

相关问题