由于您没有指定示例 df,因此我创建了自己的示例。
要手动指定颜色,您必须使用带有命名向量的scale_fill_manual 作为values 的参数。
编辑 2
这似乎可以满足您的需求。我们使用scale_y_continuous。 breaks 参数指定位置向量,而 labels 参数指定应出现在这些位置的标签。由于我们在创建数据框时已经创建了向量,因此我们只需将这些向量作为参数传递。
ggplot(df, aes(x = order, y = mean, size = n, fill = name)) +
geom_point(shape = 21) +
scale_fill_manual(values = gcolors) +
scale_size(limits = c(min(df$n), max(df$n))) +
scale_y_continuous(breaks = mean, labels = order_label)
编辑 1
根据您的评论,您似乎想要标记这些圈子。一种选择是使用geom_text。代码如下。您可能需要尝试使用 nudge_y 的值来获得正确的位置。
order <- c(1, 2)
mean <- c(0.75, 0.3)
n <- c(180, 200)
name <- c("a", "b")
order_label <- c("New York", "London")
df <- data.frame(order, mean, n, name, order_label, stringsAsFactors = FALSE)
color <- c("blue", "red")
name_color <- data.frame(name, color, stringsAsFactors = FALSE)
gcolors <- name_color[, 2]
names(gcolors) <- name_color[, 1]
ggplot(df, aes(x = order, y = mean, size = n, fill = name)) +
geom_point(shape = 21) +
geom_text(aes(label = order_label), size = 3, hjust = "inward",
nudge_y = 0.03) +
scale_fill_manual(values = gcolors) +
scale_size(limits = c(min(df$n), max(df$n))) +
theme(axis.text.y = element_blank(),
axis.ticks.y = element_blank()) +
ylab(NULL)
原答案
不清楚您所说的“用 y 上的数字代替文本标签”是什么意思。在下面的示例中,我使用 scales::percent_format() 函数将 y 轴格式化为百分比。这和你想要的一样吗?
order <- c(1, 2)
mean <- c(0.75, 0.3)
n <- c(180, 200)
name <- c("a", "b")
df <- data.frame(order, mean, n, name, stringsAsFactors = FALSE)
color <- c("blue", "red")
name_color <- data.frame(name, color, stringsAsFactors = FALSE)
gcolors <- name_color[, 2]
names(gcolors) <- name_color[, 1]
ggplot(df, aes(x = order, y = mean, size = n, fill = name)) +
geom_point(shape = 21) +
scale_fill_manual(values = gcolors) +
scale_size(limits = c(min(df$n), max(df$n))) +
scale_y_continuous(labels = scales::percent_format())