简体   繁体   中英

position = position_stack(0.5) does not centralize the annotations

my dataset is something like:

structure(list(title = c("Fried Anchovies with Sage", "Anchovies Appetizer With Breadcrumbs & Scallions", 
"Carrots, Cauliflower And Anchovies", "Bap Story: Stir Fried Anchovies (Myulchi Bokkeum)", 
"Fried Anchovies"), pricePerServing = c(5.6051, 0.8206, 4.38, 
8.1122, 1.505), healthScore = c(29, 4, 63, 70, 6), readyInMinutes = c(45L, 
15L, 45L, 45L, 15L), veryHealthy = c("False", "False", "True", 
"True", "False"), dairyFree = c("True", "True", "True", "True", 
"True"), dishType = c("lunch", "antipasti", "lunch", "lunch", 
"antipasti"), healthy = c(0.752433090024331, 0.752433090024331, 
0.247566909975669, 0.247566909975669, 0.752433090024331), diary = c(0.423965936739659, 
0.423965936739659, 0.423965936739659, 0.423965936739659, 0.423965936739659
), percent = c(0.370250606305578, 0.370250606305578, 0.587223587223587, 
0.587223587223587, 0.370250606305578)), row.names = c(NA, 5L), class = "data.frame")

my code is:


ggplot(foods, aes(x=veryHealthy, y=diary, width=healthy , fill = dairyFree)) + 
    geom_bar(position="fill", stat='identity') +
    scale_x_discrete(expand = c(0, 0)) +
    facet_grid(~veryHealthy, scales = "free", space = "free") +
    geom_text(aes(label = percent), colour = "white")

my first picture looks like this: 在此处输入图像描述 I want to make the labels on the middle of each bar so I use position = position_stack(0.5) and my code after modification is:

  ggplot(foods, aes(x=veryHealthy, y=diary, width=healthy , fill = dairyFree)) + 
    geom_bar(stat='identity') +
    scale_x_discrete(expand = c(0, 0)) +
    facet_grid(~veryHealthy, scales = "free", space = "free") +
    geom_text(aes(label = percent), position = position_stack(0.5))

and then I get: 在此处输入图像描述

my problem is not changing the height but it is those ugly black lines.

what should I do?

You are trying to write geom_text as many times as the number of records in each bar. When you use position_stack , it displays all those records, and hence the weird looking plot. If you want to display the labels only once in each bar, you need to aggregate it accordingly and use the aggregate data in geom_text . Try this

agg.data <- aggregate(percent ~ veryHealthy + diary + healthy + dairyFree, data = foods, mean)

ggplot(foods, aes(x=veryHealthy, y=diary, width=healthy , fill = dairyFree)) + 
   geom_bar(stat='identity') +
   scale_x_discrete(expand = c(0, 0)) +
   facet_grid(~veryHealthy, scales = "free", space = "free") +
   geom_text(data = agg.data, aes(label = percent)) 

输出

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM