Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to label only the modal peak in a geom_col plot

I'd like to put a label above only the modal bar (the tallest peak) on my geom_col plot, giving the x-axis value (CAG). Here's an example, but I can only get it to label every peak.

x <- seq(-20, 20, by = .1)
y <- dnorm(x, mean = 5.0, sd = 1.0)
z <- data.frame(CAG = 1:401, height = y)
ggplot(z, aes(x=CAG, y=height)) +
  geom_col() +
  geom_text(aes(label = CAG))

I'd be very grateful for help with labelling only the top peak

like image 820
Mike Avatar asked Apr 17 '20 08:04

Mike


People also ask

Should data be arranged by the label column before calling Geom_text ()?

Therefore data should be arranged by the label column before calling geom_text (). Note that this argument is not supported by geom_label (). Note that when you resize a plot, text labels stay the same size, even though the size of the plot area changes. This happens because the "width" and "height" of a text element are 0.

How to use Geom_Col in bar chart?

Bar chart. geom_col makes the height of the bar from the values in dataset. bar width. By default, set to 90% of the resolution of the data Using the described geometry, you can insert a simple geometric object into your data visualization – bar layer that is defined by two positional aesthetic properties ( x and y ).

How to use Geom_text () and Geom_label ()?

They can be used by themselves as scatterplots or in combination with other geoms, for example, for labeling points or for annotating the height of bars. geom_text () adds only text to the plot. geom_label () draws a rectangle behind the text, making it easier to read. Set of aesthetic mappings created by aes () or aes_ ().

What is Check_overlap in Geom_text?

If TRUE, text that overlaps previous text in the same layer will not be plotted. check_overlap happens at draw time and in the order of the data. Therefore data should be arranged by the label column before calling geom_text (). Note that this argument is not supported by geom_label ().


1 Answers

Just subset your dataset in geom_text to keep only the maximal value of y:

ggplot(z, aes(x=CAG, y=height)) +
  geom_col() +
  geom_text(data = subset(z, y == max(y)), aes(label = CAG))

enter image description here

like image 127
dc37 Avatar answered Nov 15 '22 07:11

dc37