【发布时间】:2021-08-01 01:55:39
【问题描述】:
这个问题建立在enter link description here提供的这个解决方案之上
如下。
library(ggplot2)
library(gtable)
library(grid)
diamonds$cut = factor(diamonds$cut, levels=c("Fair","Good"," ","Very Good",
"Premium","Ideal"))
p = ggplot(diamonds, aes(color, fill = cut)) +
geom_bar() +
scale_fill_manual(values =
c(hcl(seq(15, 325, length.out = 5), 100, 65)[1:2],
"white",
hcl(seq(15, 325, length.out = 5), 100, 65)[3:5]),
drop = FALSE) +
guides(fill = guide_legend(ncol = 2, title.position = "top")) +
theme(legend.position = "bottom",
legend.key = element_rect(fill = "white"))
# Get the ggplot grob
g = ggplotGrob(p)
# Get the legend
leg = g$grobs[[which(g$layout$name == "guide-box")]]$grobs[[1]]
# Set up the two sub-titles as text grobs
st = lapply(c("First group", "Second group"), function(x) {
textGrob(x, x = 0, just = "left", gp = gpar(cex = 0.8)) } )
# Add a row to the legend gtable to take the legend sub-titles
leg = gtable_add_rows(leg, unit(1, "grobheight", st[[1]]) + unit(0.2, "cm"), pos = 3)
# Add the sub-titles to the new row
leg = gtable_add_grob(leg, st,
t = 4, l = c(2, 6), r = c(4, 8), clip = "off")
# Add a little more space between the two columns
leg$widths[[5]] = unit(.6, "cm")
# Move the legend to the right
leg$vp = viewport(x = unit(.95, "npc"), width = sum(leg$widths), just = "right")
# Put the legend back into the plot
g$grobs[[which(g$layout$name == "guide-box")]] = leg
# Draw the plot
grid.newpage()
grid.draw(g)
这提供了图(从那里)。
但是,我想做两件事。
-
第一组:我想将“Fair”和“Good”分别重新标记为“Very Good”和“Premium”。所以他们在每组(第一和第二)中都非常好和优质。
-
我想做的第二件事是将它们放在一行中(第一组和第二组的两列并排,所有内容都在一行中,以节省垂直空间。
我该怎么做?如果我的问题不清楚,请告诉我。我觉得我在这里很近,但这个解决方案并不能完全回答我的问题。非常感谢!
【问题讨论】:
-
您的问题似乎不清楚。(不鼓励多部分问题。)为什么不在 ggplot 调用之前修改 data 参数?并放入“一条线”?这是什么意思?