Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
494 views
in Technique[技术] by (71.8m points)

r - ggplot piecharts on a ggmap: labels destroy the small plots

My ggmap on which I would like small piecharts with labels is generated with the code:

p <-
  get_googlemap(
    "Poland",
    maptype = "roadmap",
    zoom = 6,
    color = "bw",
    crop = T,
    style = 'feature:all|element:labels|visibility:off'  #'feature:administrative.country|element:labels|visibility:off' or 'feature:all|element:labels|visibility:off'
  ) %>% 
  ggmap() + coord_cartesian() +
  scale_x_continuous(limits = c(14, 24.3), expand = c(0, 0)) +
  scale_y_continuous(limits = c(48.8, 55.5), expand = c(0, 0))

I am trying to plot my small ggplot piecharts on a ggmap following the answer R::ggplot2::geom_points: how to swap points with pie charts?

I prepare data as follows:

df <-
  df %>%  mutate(Ours = Potential  * MS, Others = Potential - Ours) %>%
  na.omit() %>% filter(Potential > 0) %>%
  select(-L.p., -MS) %>%
  group_by(Miasto) %>%
  summarise_each_(vars = c("Potential", "Ours", "Others"),
                  funs = funs(Sum = "sum")) %>%
  left_join(coordinatesTowns, by = c("Miasto" = "address")) %>% 
  distinct(Miasto, .keep_all = T) %>% 
  select(-X) %>% ungroup()

df <-df  %>%  gather(key=component, value=sales, c(Ours_Sum,Others_Sum)) %>% 
  group_by(lon, lat,Potential_Sum)

My data looks then like

tibble::tribble(
       ~Miasto, ~Potential_Sum,     ~lon,     ~lat,    ~component, ~sales,
   "Bialystok",            100, 23.16433, 53.13333,    "Ours_Sum",     70,
   "Bialystok",            100, 23.16433, 53.13333,  "Others_Sum",     30,
   "Bydgoszcz",             70, 18.00762,  53.1235,    "Ours_Sum",      0,
   "Bydgoszcz",             70, 18.00762,  53.1235,  "Others_Sum",     70,
      "Gdansk",             50, 18.64637, 54.35205,    "Ours_Sum",     25,
      "Gdansk",             50, 18.64637, 54.35205,  "Others_Sum",     75,
    "Katowice",             60, 19.02754, 50.25842,    "Ours_Sum",     20,
    "Katowice",             60, 19.02754, 50.25842,  "Others_Sum",     40
  )

The last line group_by is essential for generating plots that will be pasted into my map. (I suspected maybe here is the reason of my problems described below).

Instead of totals, I would like to provide labels for each share in a piechart

In this answer I found the syntax, that should add labels to the piecharts https://stackoverflow.com/a/22804400/3480717

Below is the syntax in my script the line with geom_text (commented with hash) if uncommented, causes my plots to disappear and a long list (16 entries) for all small plots, of warnings:

1: Removed 1 rows containing missing values (geom_col).

I presume the reason can be in the last line of preparing the data, grouping it for the plotting.

The line I mark with a hash is a problem. If I put the hash plots are correct, if I include it, trying to get the desired labels on the slices, plots disappear or are very narrow vertical slices.

       df.grobs <- df %>% 
      do(subplots = ggplot(., aes(1, sales, fill = component)) + 
           geom_bar(position = "fill", alpha = 0.5, colour = "white", stat="identity") + 
#          geom_text( aes(label = round(sales), y=sales), position = position_stack(vjust = 0.5), size = 2.5)  +
           coord_polar(theta = "y") + 
           scale_fill_manual(values = c("green", "red"))+
           theme_void()+ guides(fill = F)) %>% 
      mutate(subgrobs = list(annotation_custom(ggplotGrob(subplots), 
                                               x = lon-Potential_Sum/300, y = lat-Potential_Sum/300, 
                                               xmax = lon+Potential_Sum/300, ymax = lat+Potential_Sum/300))) 

    df.grobs


    df.grobs %>%
    {p + 
        .$subgrobs + 
                geom_col(data = df,
                 aes(0,0, fill = component), 
                 colour = "white")+ geom_text(data=df, aes(label = Miasto),nudge_y = -0.15, size=2.5)}

Why is the line marked with a hash (if uncommented) destroying the plot instead of adding labels? It seems to completely redefine aesthetics.

EDIT: I modified the marked line, now label=sales and y=sales. Now if I comment the line, the plots are generated, if I uncomment it, the labels are generated in correct position but without plots. Why I cannot have both?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Short answer:

I think the problem is actually in your earlier line:

geom_bar(position = "fill", alpha = 0.5, colour = "white", stat="identity") +

If you change the position from fill to stack (i.e. the default), it should work properly (at least it did on mine).

Long(-winded) explanation:

Let's use a summarised version of the mtcars dataset to reproduce the problem:

dfm <- mtcars %>% group_by(cyl) %>% summarise(disp = mean(disp)) %>% ungroup()

# correct pie chart
ggplot(dfm, aes(x = 1, y = disp, label = factor(cyl), fill = factor(cyl))) + 
  geom_bar(stat = "identity", position = "stack") + 
  geom_text(position = position_stack(vjust = 0.5)) + 
  coord_polar(theta = "y") + theme_void()

# "empty" pie chart
ggplot(dfm, aes(x = 1, y = disp, label = factor(cyl), fill = factor(cyl))) + 
  geom_bar(stat = "identity", position = "fill") + 
  geom_text(position = position_stack(vjust = 0.5)) + 
  coord_polar(theta = "y") + theme_void()

Correct version

Problematic version

Why does changing geom_bar's position affect this? If we look at the plot before the coord_polar step, things may become clearer:

ggplot(dfm, aes(x = 1, y = disp, label = factor(cyl), fill = factor(cyl))) + 
  geom_bar(stat = "identity", position = "stack") + 
  geom_text(position = position_stack(vjust = 0.5))

Correct bar chart

Check the bar chart's y-axis. The bars & the labels are correctly positioned.

Now the version with position = "fill":

ggplot(dfm, aes(x = 1, y = disp, label = factor(cyl), fill = factor(cyl))) + 
  geom_bar(stat = "identity", position = "fill") + 
  geom_text(position = position_stack(vjust = 0.5))

Problematic bar chart

Your bar chart now occupies the range 0-1 on the y-axis, while your labels continue to occupy the original full range, which is much larger. Thus when you convert the chart to polar coordinates, the bar chart is squeezed to a tiny slice that becomes practically invisible.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...