这是this分的跟进问题.

请考虑以下修改后的示例:

library(ggplot2)

ggplot(mtcars, aes(x = factor(am), y = mpg, color = factor(am))) +
  geom_point(shape = 15, size = 6, alpha = 0.7,
             position = position_jitter(width = 0.25, height = 0, seed = 31)) +
  geom_text(aes(label = am), 
            position = position_jitter(width = 0.25, height = 0, seed = 31), 
            size = 3, color = "black") 

enter image description here

How can I put the 0 and 1 in the legend into the the squares? I would expect this: enter image description here

我找到的最接近的解决方案是here.

推荐答案

将我的答案从参考文章中改编到你的 case 中,你可以像这样实现你想要的结果:

注意:基本上这需要用draw_key_point替换draw_key_rect,使用color而不是fill,调整key_label数据帧并使用不同的调色板.此外,我还删除了用于调整键宽度的代码,至少对于您的示例数据来说,这不是必需的.最后,我通过theme个选项删除了图例文本.

library(ggplot2)
library(dplyr, warn = FALSE)

# Color palette
pal <- scales::hue_pal()(2)
names(pal) <- c("0", "1")

# Legend key labels
key_label <- mtcars |>
  distinct(am) |>
  mutate(key_label = am) |>
  tibble::deframe()

# Custom key glyph
draw_key_cust <- function(data, params, size) {
  data_text <- data
  data_text$label <- key_label[names(pal)[match(data$colour, pal)]]
  data_text[c("fill", "shape", "stroke")] <- NULL
  data_text$colour <- "black"
  data_text$size <- 11 / .pt

  grid::grobTree(
    draw_key_point(data, list()),
    draw_key_text(data_text, list())
  )
}

library(ggplot2)

ggplot(mtcars, aes(x = factor(am), y = mpg, color = factor(am))) +
  geom_point(
    shape = 15, size = 6, alpha = 0.7,
    position = position_jitter(width = 0.25, height = 0, seed = 31),
    key_glyph = "cust"
  ) +
  geom_text(aes(label = am),
    position = position_jitter(width = 0.25, height = 0, seed = 31),
    size = 3, color = "black"
  ) +
  theme(
    legend.text = element_blank()
  )

R相关问答推荐

在R中查找每个组不同时间段的总天数

R等效于LABpascal(n,1)不同的列符号

r替换lme S4对象的字符串的一部分

二维样条,严格以一个参数递增

如何直接从R中的风险分数计算c指数?

R中插入符号训练函数的中心因子和尺度因子预测

在数组索引上复制矩阵时出错

ComplexHEAT:使用COLUMN_SPLIT时忽略COLUMN_ORDER

从非重叠(非滚动)周期中的最新数据向后开窗并在周期内计数

根据另一列中的值和条件查找新列的值

根据纬度和距离连接两个数据集

当每个变量值只能 Select 一次时,如何从数据框中 Select 两个变量的组合?

`-`是否也用于数据帧,有时使用引用调用?

无法将条件case_when()应用于使用!!创建的新变量Mutations

数值型数据与字符混合时如何进行绑定

如何为混合模型输出绘制不同的线型?

在shiny 表格中输入的文本在第一次后未更新

以R表示的NaN值的IS.NA状态

reshape 数据帧-基于组将行转换为列

移除y轴断开的geom_bar图的外框