2014-07-17 17 views
20

Chcę dodać etykiety danych na fasetce z masą.
Może ktoś może mi pomóc.R + ggplot2 => dodaj etykiety na wykresie kołowym aspektu

Moje dane:

year <- c(1,2,1,2,1,2) 
prod <- c(1,1,2,2,3,3) 
quantity <- c(33,50,33,25,34,25) 

df <- data.frame(year, prod, quantity) 
rm(year, prod, quantity) 

Kod:

library(ggplot2) 

# center's calculated by hand 
centr2 <- c(16, 25, 49, 62.5, 81, 87.5) 

ggplot(data=df, aes(x=factor(1), y=quantity, fill=factor(prod))) + 
    geom_bar(stat="identity") + 
    geom_text(aes(x= factor(1), y=centr2, label = df$quantity), size=10) + 
    facet_grid(facets = .~year, labeller = label_value) + 
    coord_polar(theta = "y") 

A mój wynik to:

pie char

Jeśli usunąć coord_polar (theta = "y"), I będzie mieć następującą działkę:

bar plot

A teraz jest dla mnie jasne, dlaczego moje etykiety danych nie pasują do siebie.
Ale nie wiem jak to naprawić.

czytam:
1. Place labels on Pie Chart
2. Add text to ggplot with facetted densities
3. Pie plot getting its text on top of each other

Ale nie znaleźliśmy odpowiedź.

Odpowiedz

20

Podejdę do tego, definiując inną zmienną (którą nazywam pos) w df, która oblicza pozycję etykiet tekstowych. Robię to z dplyr, ale możesz również użyć innych metod.

library(dplyr) 
library(ggplot2) 

df <- df %>% group_by(year) %>% mutate(pos = cumsum(quantity)- quantity/2) 

ggplot(data=df, aes(x=factor(1), y=quantity, fill=factor(prod))) + 
    geom_bar(stat="identity") + 
    geom_text(aes(x= factor(1), y=pos, label = quantity), size=10) + # note y = pos 
    facet_grid(facets = .~year, labeller = label_value) + 
    coord_polar(theta = "y") 

pie

+0

mógłbyś wyjaśnić uzasadnienie, w jaki sposób można obliczyć położenie liczb? – Kots

Powiązane problemy