
換句話說,我有一組帶有自定義文本的顏色串列,我希望它們都包含在圖例中,而不管繪圖中使用的顏色是什么。
我想要的圖例顏色存盤在物件圖表中:
chart <- structure(list(plotvals = c(0.2, 0.4, 0.6, 0.8, 1), Colour = c(
"#000080", "#87CEFA", "#00FF00", "#FFA500", "#FF0000")), row.names = c(1L,
2L, 3L, 4L, 5L), class = "data.frame")
> chart
plotvals Colour
1 0.2 #000080
2 0.4 #87CEFA
3 0.6 #00FF00
4 0.8 #FFA500
5 1.0 #FF0000
我可以按如下方式在左側創建圖:
df <- structure(list(pos = c(82304304L, 82402792L, 82567842L, 82646930L,
82686681L), val = c(0.0336705048361217, 0.0304909014034332, 3.21204387671607,
2.28366271211045, 1.7182850299727), Colour = c("#000080", "#000080",
"#87CEFA", "#00FF00", "#87CEFA")), row.names = c(1L, 2L, 3L,
4L, 5L), class = "data.frame")
> df
pos val Colour
1 82304304 0.0336705 #000080
2 82402792 0.0304909 #000080
3 82567842 3.2120439 #87CEFA
4 82646930 2.2836627 #00FF00
5 82686681 1.7182850 #87CEFA
plot1 <- ggplot(df, aes(pos, rep(1, times = nrow(df))))
geom_point(shape = "\u007C", size = 5)
theme_void()
plot2 <- ggplot(df, aes(pos, val, colour = Colour))
geom_point()
ylim(0, 4)
theme_bw()
scale_color_identity(guide = "legend")
plots <- ggarrange(plot1, plot2, heights = c(0.5, 6),
ncol = 1, nrow = 2, align = "v", common.legend = TRUE, legend = "right")
png("plots.png")
plots
dev.off()
如何調整圖例,使其成為自定義圖例,但仍可與 ggarrange 一起使用?
uj5u.com熱心網友回復:
不確定這是否適用于您的實際情況,但對于示例資料,一個選項是根據您的df 加上一些額外的技巧來設定色階的limits和,即使用矩形并設定:labelschartguide_legendshapesize
library(ggplot2)
library(ggpubr)
plot1 <- ggplot(df, aes(pos, rep(1, times = nrow(df))))
geom_point(shape = "\u007C", size = 5)
theme_void()
plot2 <- ggplot(df, aes(pos, val))
geom_point(aes(colour = Colour))
theme_bw()
scale_color_identity(
guide = guide_legend(reverse = TRUE, override.aes = list(shape = 15, size = 5)),
limits = chart$Colour, labels = scales::number(chart$plotvals)
)
scale_fill_manual(values = chart$Colour)
plots <- ggarrange(plot1, plot2,
heights = c(0.5, 6),
ncol = 1, nrow = 2, align = "v", common.legend = TRUE, legend = "right"
)

轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/535928.html
標籤:r图表2
