Reputation: 11
I want to illustrate the changes in number of chinese lawyers from 2017 to 2021. I was successful in doing that. But I want to add data value labels at the ends of the line graph to illustrate before and after.
Here's the code :
category<-total_lawyers|>
pivot_longer(cols =2:6, names_to = "year", values_to = "total" )
category|>
ggplot(aes(year, total, group=category,color=category))+
geom_line(size=1.5)+scale_y_log10()+
theme_stata()+
theme(axis.title.y = element_blank(),
axis.title.x = element_blank())[
](https://i.sstatic.net/uuSIS.png)
what I want is to add to add data labels only at both ends.
Upvotes: 0
Views: 46
Reputation: 1316
Besides doing manual annotations as in the comment you can filter your data to just the data you want to highlight and then let ggplot do all the aesthetic mapping for you. Here is an example using the built in mtcars
dataset. The dataset is filtered to obtain the minimum or maximum of the value plotted on the x-axis and then those points plotted with an additional geom using that filtered data set:
library(dplyr)
library(ggplot2)
data_to_highlight <-
mtcars |>
group_by(cyl) |>
filter(disp == min(disp) | disp == max(disp))
ggplot()+
geom_line(data = mtcars,
aes(x = disp,
y = mpg,
color = as.factor(cyl)))+
geom_point(data = data_to_highlight,
aes(x = disp,
y = mpg,
color = as.factor(cyl)))
Note: You also can map the values as text and do some more fun stuff. Here the min/max points of the disp
variable is highlighted with points and the corresponding mpg
values written in text:
ggplot()+
geom_line(data = mtcars,
aes(x = disp,
y = mpg,
color = as.factor(cyl)))+
geom_point(data = data_to_highlight,
aes(x = disp,
y = mpg,
color = as.factor(cyl)),
size = 6, shape = 16)+
geom_text(data = data_to_highlight,
aes(x = disp,
y = mpg,
label = mpg),
size = 2,
color = "white")
Upvotes: 1