我在 R 方面很新颖,我正在用 ggplot2 绘制一个情节,我想更改图例中我的点的颜色(与情节中的颜色相同)
p1 <- ggplot(reliability.plot, aes(x = reorder(Class, -cost_bil),
y = Implementation)) +
geom_point( aes(size=cost_bil), color = col) +
scale_size(range=c(1,30),
breaks=c(0.1,1,2,5,10,20,30)) +
rotate_x_text(45)+rotate_y_text(45)+
guides(size=guide_legend(reverse = T)) +
labs(size="US$ billions")+
theme(legend.key=element_rect(fill=NA)+
xlab("Taxonomic Class") +
ylab("Method reliability") +
theme(text = element_text(size=12)) +
geom_text(aes(label=n),hjust=0.5, vjust=2.5) +
theme_bw()+
theme_classic()
答案 0 :(得分:0)
感谢您提供minimal reproducible example;以下是我将如何解决您的问题:
# Load libraries
library(tidyverse)
# Load example dataset
example_dataset <- structure(list(ID = 1:6,
Class = c("Amphibia", "Diverse", "Reptilia", "Amphibia", "Diverse", "Reptilia"),
Implementation = structure(c(1L, 1L, 1L, 2L, 2L, 2L),
.Label = c("Observed", "Potential"),
class = "factor"),
cost_bil = c(16.78812696789, 0.00755587011, 3.81210675659,
46.26621554247, 0.32702350757, 110.57066587724),
n = c(58190L, 9L, 2482L, 40748L, 3L, 16326L)),
row.names = c(NA, -6L), class = "data.frame")
# Make "Class" a factor
example_dataset$Class <- factor(example_dataset$Class)
# Create a color palette to map to continuous values
my_pal <- colorRampPalette(c("yellow","firebrick2"))
# Plot the data
ggplot(example_dataset, aes(x = reorder(Class, -cost_bil), y = Implementation)) +
geom_point(aes(size = cost_bil, color = cost_bil)) +
geom_text(aes(label = paste("n =", scales::comma(n, accuracy = 1), sep = " ")),
nudge_y = 0.3) +
scale_color_gradientn(colours = my_pal(6)) +
scale_size_continuous(range = c(5, 30)) +
guides(color = guide_legend(reverse = T),
size = guide_legend(reverse = T)) +
labs(size = "US$ billions", color = "US$ billions") +
xlab("Taxonomic Class") +
ylab("Method reliability") +
theme_bw(base_size = 16)
如果将 cost_bil 更改为因子并使用 scale_color_manual()
,则可以为此类图选择离散颜色,但这并不简单。如果这真的是您想要做的(即列出每个点的特定颜色),我可能会弄清楚如何去做,但这并不容易,也不会“有意义”(即颜色与值的变化无关)