将数据标签添加到ggplot中的点:label参数不起作用

时间:2018-04-24 05:37:43

标签: r ggplot2

我知道这个问题已被回复了几次herehere。关键点似乎是在label中包含参数aes。但是,对我而言,ggplot不接受label作为aes中的参数。我尝试在下面的aes中使用泛型函数labels,但这并不能为点创建标签,尽管我能够生成图表:

  launch_curve <- ggplot(data = saltsnck_2002_plot_t,aes(x=weeks,y=markets, labels(c(1,2,3,4,5,6,7,8,9,10,11,12))))+
    geom_line()+geom_point()+
    scale_x_continuous(breaks = seq(0,12,by=1))+
    scale_y_continuous(limits=c(0,50), breaks = seq(0,50,by=5))+
    xlab("Weeks since launch")+ ylab("No. of markets")+
    ggtitle(paste0(marker1,marker2))+
    theme(plot.title = element_text(size = 10))
  print(launch_curve)

有没有人知道解决这个问题的方法?我使用的是R版本3.4.3。

已修改为包含示例数据 我用于绘制的数据位于数据框saltsnck_2002_plot_t中。 (12行乘94列)。下面给出了一个样本:

>saltsnck_2002_plot_t

       11410008398 11600028960 11819570760 11819570761 12325461033 12325461035 12325461037
Week1            3           2           2           1           2           2           1
Week2            6          16          10           1           3           2           2
Week3           11          41          13          10           3           3           2
Week4           15          46          14          14           3           4           4
Week5           15          48          15          14           3           4           4
Week6           27          48          15          15           3           4           4
Week7           31          50          15          15           3           4           5
Week8           33          50          16          16           5           5           6
Week9           34          50          18          16           5           5           6
Week10          34          50          21          19           5           5           6
Week11          34          50          23          21           5           5           6
Week12          34          50          24          23           5           5           6

我实际上是通过移动数据框的列来绘制循环中的图形。此数据帧是转置操作的结果,因此是奇怪的行和列名称。第一列的图形如下所示。从我之前的帖子中得到的修正,我需要捕获列中值的数据标签,而不是c(1,2,3,4,5,6,7,8,9,10,11,12)。 / p>

enter image description here

1 个答案:

答案 0 :(得分:0)

dput(df)

df <- structure(list(weeks_num = c(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 
12), weeks = structure(1:12, .Label = c("week1", "week2", "week3", 
"week4", "week5", "week6", "week7", "week8", "week9", "week10", 
"week11", "week12"), class = c("ordered", "factor")), markets = c(3, 
 6, 11, 15, 27, 31, 33, 34, 34, 34, 34, 34)), .Names = c("weeks_num", 
"weeks", "markets"), row.names = c(NA, -12L), class = "data.frame")

 ggplot(data = df,aes(x=weeks_num,y=markets))+
 geom_line()+geom_point()+ geom_text(aes(label = weeks), hjust = 0.5,  vjust = -1) +
 scale_y_continuous(limits=c(0,50), breaks = seq(0,50,by=5)) +
 scale_x_continuous(breaks = seq(1,12,by=1),labels = weeks_num)+
 xlab("Weeks since launch")+ ylab("No. of markets")+
 ggtitle(paste0(markets))+
 theme(plot.title = element_text(size = 10))

enter image description here

我希望它有所帮助;)