ggplot添加手动传说绘图而无需修改数据集

发布于 2025-01-21 23:54:51 字数 857 浏览 2 评论 0原文

我试图在图块中添加手动传说而不修改数据集,因为数据集和标记平均值,中位数等的行是不同的概念

解决了修改数据的问题的方法,例如添加手动传说>

这是一个简化的示例,真正的数据集更为复杂:

vec <-c(rep(1,100),rep(2,100),rep(3,80),rep(4,70),rep(5,60))
tbl <- as_tibble(vec)

mean_vec <- mean(vec)

cols <- c("Frequency"="grey",
          "mean"="blue")

ggplot(as_tibble(tbl)) + 
  aes(x = value) +
  geom_histogram(binwidth=1) +
  geom_vline(xintercept=mean_vec,col="blue",size=1)+
  theme_minimal() +
  scale_color_manual(values=cols)+
  scale_fill_manual(name="Test",values=cols) 

为什么图中缺少传说?

I am trying to add a manual legend to a plot without modifying the dataset, because the dataset and lines that mark mean, median etc. are different concepts.

Approaches to solve the problem modifying the data exist, e.g. Adding manual legend to a ggplot

Here is a simplified example, the real dataset is more complex:

vec <-c(rep(1,100),rep(2,100),rep(3,80),rep(4,70),rep(5,60))
tbl <- as_tibble(vec)

mean_vec <- mean(vec)

cols <- c("Frequency"="grey",
          "mean"="blue")

ggplot(as_tibble(tbl)) + 
  aes(x = value) +
  geom_histogram(binwidth=1) +
  geom_vline(xintercept=mean_vec,col="blue",size=1)+
  theme_minimal() +
  scale_color_manual(values=cols)+
  scale_fill_manual(name="Test",values=cols) 

Why is the legend missing in the plot?

Histogram with mean line. The legend is missing in the plot

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

旧人哭 2025-01-28 23:54:51

如果您想拥有一个传奇,则必须绘制美学绘制。否则scale_color/fill_manual将无效:

vec <- c(rep(1, 100), rep(2, 100), rep(3, 80), rep(4, 70), rep(5, 60))
tbl <- data.frame(value = vec)

mean_vec <- mean(vec)

cols <- c(
  "Frequency" = "grey",
  "mean" = "blue"
)

library(ggplot2)

ggplot(tbl) +
  aes(x = value) +
  geom_histogram(aes(fill = "Frequency"), binwidth = 1) +
  geom_vline(aes(color = "mean", xintercept = mean_vec), size = 1) +
  theme_minimal() +
  scale_color_manual(values = "blue") +
  scale_fill_manual(name = "Test", values = "grey")

“”

If you want to have a legend then you have to map on aesthetics. Otherwise scale_color/fill_manual will have no effect:

vec <- c(rep(1, 100), rep(2, 100), rep(3, 80), rep(4, 70), rep(5, 60))
tbl <- data.frame(value = vec)

mean_vec <- mean(vec)

cols <- c(
  "Frequency" = "grey",
  "mean" = "blue"
)

library(ggplot2)

ggplot(tbl) +
  aes(x = value) +
  geom_histogram(aes(fill = "Frequency"), binwidth = 1) +
  geom_vline(aes(color = "mean", xintercept = mean_vec), size = 1) +
  theme_minimal() +
  scale_color_manual(values = "blue") +
  scale_fill_manual(name = "Test", values = "grey")

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文