我在R中有一个散点图。每个(x,y)
点都根据其z
值着色。因此,您可以将每个点视为(x,y,z)
,其中(x,y)
确定其位置,z
沿颜色渐变确定其颜色。我想补充两件事
z
值对应的颜色这是我目前的代码及其制作的图像。
x <- seq(1,150)
y <- runif(150)
z <- c(rnorm(mean=1,100),rnorm(mean=20,50))
colorFunction <- colorRamp(rainbow(100))
zScaled <- (z - min(z)) / (max(z) - min(z))
zMatrix <- colorFunction(zScaled)
zColors <- rgb(zMatrix[,1], zMatrix[,2], zMatrix[,3], maxColorValue=255)
df <- data.frame(x,y)
x <- densCols(x,y, colramp=colorRampPalette(c("black", "white")))
df$dens <- col2rgb(x)[1,] + 1L
plot(y~x, data=df[order(df$dens),],pch=20, col=zColors, cex=1)
答案 0 :(得分:7)
以下是使用ggplot2
包的一些解决方案。
# Load library
library(ggplot2)
# Recreate the scatterplot from the example with default colours
ggplot(df) +
geom_point(aes(x=x, y=y, col=dens))
# Recreate the scatterplot with a custom set of colours. I use rainbow(100)
ggplot(df) +
geom_point(aes(x=x, y=y, col=dens)) +
scale_color_gradientn(colours=rainbow(100))
# A 2d density plot, using default colours
ggplot(df) +
stat_density2d(aes(x=x, y=y, z=dens, fill = ..level..), geom="polygon") +
ylim(-0.2, 1.2) + xlim(-30, 180) # I had to twiddle with the ranges to get a nicer plot
# A better density plot, in my opinion. Tiles across your range of data
ggplot(df) +
stat_density2d(aes(x=x, y=y, z=dens, fill = ..density..), geom="tile",
contour = FALSE)
# Using custom colours. I use rainbow(100) again.
ggplot(df) +
stat_density2d(aes(x=x, y=y, z=dens, fill = ..density..), geom="tile",
contour = FALSE) +
scale_fill_gradientn(colours=rainbow(100))
# You can also plot the points on top, if you want
ggplot(df) +
stat_density2d(aes(x=x, y=y, z=dens, fill = ..density..), geom="tile",
contour = FALSE) +
geom_point(aes(x=x, y=y, col=dens)) +
scale_colour_continuous(guide=FALSE) # This removes the extra legend
我也附上了这些情节:
答案 1 :(得分:1)
此外,使用ggplot2,您可以一起使用颜色和大小,如:
ggplot(df, aes(x=x, y=y, size=dens, color=dens)) + geom_point() +
scale_color_gradientn(name="Density", colours=rev(rainbow(100))) +
scale_size_continuous(range=c(1,15), guide="none")
这可能会让它更清晰一些。
注意:
表达式rev(rainbow(100))
颠倒了彩虹色标,
因此红色与dens
的较大值相符。
不幸的是,您无法组合连续的图例(颜色)和a
离散的图例(大小),所以你通常会得到两个传说。该
表达式guide="none"
隐藏了大小图例。
这是情节: