R ggplot2 标签排序 (geom_text)

R ggplot2 ordering of labels (geom_text)

我有一个图表,它显示了条形图和折线图的组合。现在我想在图中添加标签,但它们都绘制在一条线上而不是正确的位置。

这是我使用的 df:

df1 <- data.frame(cat = c("category1", "category2", "category3", 
                            "category1", "category2", "category3",
                            "category1", "category2", "category3"), 
                  source = c("a", "a", "a", "b", "b", "b", "c", "c", "c"),
                  value = c(sample (c(1000L:6000L),9, replace = FALSE)),
                  stringsAsFactors = FALSE)

绘图代码:

library(dplyr)
library(ggplot2)
library(scales)

ggplot(df1) +
  geom_bar(data = filter(df1, source %in% c("a", "b")), aes(cat, value, fill = source), stat="identity", position = position_dodge()) +
  geom_point(data = filter(df1, source == "c"), aes(cat, value*5000/2000, color = source))+
  geom_line(data = filter(df1, source == "c"), aes(cat, value*5000/2000, color = source , group = source)) +
  labs(x= "categories", y= "a and b (bars)") +
  scale_y_continuous(sec.axis = sec_axis(~.*2000/5000, name = "c (line)"), 
                     labels= format_format(big.mark = ".", decimal.mark = ",", scientific = FALSE)) +
  scale_fill_manual(values= c("darkseagreen4", "darkseagreen3")) +
  geom_text(aes(label=value, x = cat, y = value), vjust = 1.5, size = 3) +
  theme_light() 

有人知道如何将标签放在正确的位置吗?

在一个图中有两个不同的 'plots' 将迫使您也有两种不同的方式来包含标签。

使用 position = position_dodge2() 解决了每个条上都有标签的问题,但这不适用于线条。只需为其添加一个新的 geom_text

df1 <- data.frame(cat = c("category1", "category2", "category3", 
                          "category1", "category2", "category3",
                          "category1", "category2", "category3"), 
                  source = c("a", "a", "a", "b", "b", "b", "c", "c", "c"),
                  value = c(sample (c(1000L:6000L),9, replace = FALSE)),
                  stringsAsFactors = FALSE)

library(dplyr)
library(ggplot2)
library(scales)

ggplot() +
  geom_col(data = filter(df1, source %in% c("a", "b")), aes(cat, value, fill = source), position = position_dodge()) +
  geom_text(data = filter(df1, source %in% c("a", "b")), aes(cat, value,label=value, group = source), vjust = 1.5, size = 3, position = position_dodge(width = 1)) +

  geom_point(data = filter(df1, source == "c"), aes(cat, value*5000/2000, color = source)) +
  geom_line(data = filter(df1, source == "c"), aes(cat, value*5000/2000, color = source , group = source)) +
  geom_text(data = filter(df1, source == "c"), aes(cat, value*5000/2000, label=value), vjust = 1.5, size = 3) +

  labs(x= "categories", y= "a and b (bars)") +
  scale_y_continuous(sec.axis = sec_axis(~.*2000/5000, name = "c (line)"), 
                     labels= format_format(big.mark = ".", decimal.mark = ",", scientific = FALSE)) +
  scale_fill_manual(values= c("darkseagreen4", "darkseagreen3")) +
  theme_light() 

reprex package (v0.2.0) 创建于 2018-05-25。