Hi there,
I want to create a plot with bars corresponding to the numeric variable “perc” (along with confidence intervals) by “food”. The data set also contains a variable “R”, with exactly the same value as perc. However, this “R” variable is a character one, and in some cases the values contains a number along with a letter (e.g. 17.7E). This letter means the coefficient of variation is > 16.6, so I want to use the values from “R” in geom_text to include them in the plot.
When the first value of “R” has the letter E (like in the example data set), the value displayed at the top of the bar looks messy. This is because “two different values” are been included in the plot. Once from “R” (e.g. 17.7E) and the other one from the result of applying cumsum (e.g. 17.7). I would like to be able to remove the label from cumsum for the first value, so that the only value that is displayed in at the top of the first bar comes from “R”. Can you please advise?
Please, see below my code as well as an example data set.
library(dplyr)
library(forcats)
library(ggplot2)
library(formattable)
plot = Dat %>%
mutate(food = fct_reorder(food,perc)) %>%
arrange(desc(food)) %>%
mutate(CumSum = cumsum(perc)) %>%
ggplot( aes(x=food, y=perc)) +
geom_bar(stat="identity", fill="skyblue", alpha=.6, width=.4) +
geom_errorbar( aes(x=food, ymin=perc-1.96SE_p, ymax=perc+1.96SE_p),
width=0.1, colour="orange", alpha=0.9, size=1.0) +
coord_flip() +
ggtitle("Top food source",) +
xlab("Food category") +
ylab("% daily contribution") +
geom_text(aes(label=R), size = 2.75, col = "gray9") +
theme_bw()+
geom_line(aes(x=food, y=cumsum(perc),group=1, linetype = "Cumulative percent"), col="black") +
geom_text(aes(y = formattable(CumSum, format = "f", digits = 1),label = CumSum),
size = 2.75, check_overlap = TRUE) +
scale_linetype_manual(values = c("Cumulative percent" = "dashed")) + labs(linetype = "")
My data file:
food | R | perc | SE_p | cv_p |
---|---|---|---|---|
red meat | 17.7E | 17.7 | 3.5 | 19.7 |
milk | 14.9 | 14.9 | 1.4 | 9.6 |
poultry | 9.8 | 9.8 | 1.6 | 16.4 |
cheese | 8.7 | 8.7 | 1.3 | 14.8 |
processed meat | 6 | 6 | 0.9 | 14.5 |
other bread products | 4.1 | 4.1 | 0.6 | 15.9 |
white bread | 2.8E | 2.8 | 0.5 | 18.7 |
whole wheat grain bread | 2.3E | 2.3 | 0.4 | 17.2 |
vegetables | 2.2 | 2.2 | 0.2 | 10 |
Thanks a lot,
A.G.
Additional relevant information.
OS: Windows 10 (64-bit)
R version: 3.6.2
R studio version: 3.5