简体   繁体   中英

How to add marginal rugs above bars of a bar chart with ggplot2

Is it possible to add marginal rug lines above bars? Using the data set below, how can you add 4 rug lines above Brazil, 8 above Canada, etc.

ctryfees <- feesctry %>% group_by(country) %>% summarise(total = sum(fees))

library(ggplot2)
library(ggthemes)

ggplot(ctryfees, aes(x = country, y = total)) +
  geom_bar(stat = "identity") + theme_tufte() +
  ggtitle("Fees Paid Law Firms per Country\nNumber of Firms Paid\n") +
  labs(x = "", y = "") +
  scale_y_continuous(label = dollar.format) +
  geom_rug(data = feesctry, mapping = aes(x = country, y = firms), sides = "top")

The code does not work after the scale_y_continuous line as it throws this error: Error: Discrete value supplied to continuous scale

在此处输入图片说明

> dput(feesctry)
structure(list(country = structure(c(1L, 1L, 1L, 1L, 2L, 3L, 
4L, 4L, 5L, 5L, 6L, 2L, 2L, 2L, 2L, 2L, 2L, 2L, 6L, 6L, 3L, 3L, 
3L, 3L), .Label = c("Brazil", "Canada", "China", "France", "Germany", 
"UK"), class = "factor"), firms = structure(c(1L, 2L, 3L, 4L, 
5L, 13L, 18L, 19L, 20L, 21L, 22L, 6L, 7L, 8L, 9L, 10L, 11L, 12L, 
23L, 24L, 14L, 15L, 16L, 17L), .Label = c("brazil1", "brazil2", 
"brazil3", "brazil4", "can1", "can2", "can3", "can4", "can5", 
"can6", "can7", "can8", "china1", "china2", "china3", "china4", 
"china5", "france1", "france2", "german1", "german2", "uk1", 
"uk2", "uk3"), class = "factor"), fees = c(80000, 80000, 80000, 
80000, 1e+05, 5e+05, 2e+05, 2e+05, 1e+05, 1e+05, 5e+05, 1e+05, 
1e+05, 1e+05, 1e+05, 1e+05, 1e+05, 1e+05, 5e+05, 5e+05, 5e+05, 
5e+05, 5e+05, 5e+05)), .Names = c("country", "firms", "fees"), row.names = c(NA, 
-24L), class = "data.frame")

From

p <- 
  ggplot(ctryfees, aes(x = country, y = total)) +
  geom_bar(stat = "identity") + theme_tufte() +
  ggtitle("Fees Paid Law Firms per Country\nNumber of Firms Paid\n") +
  labs(x = "", y = "") +
  scale_y_continuous(label = dollar_format()) 

you could try

p + geom_rug(data = transform(feesctry, id = as.numeric(country)), 
             mapping = aes(x = ave(id, id, FUN = function(x) 
                                                   x + scale(seq_along(x), scale = 50)), 
                           y = 1), 
             sides = "top")

or just

p + geom_rug(data = feesctry, 
             mapping = aes(x = jitter(as.numeric(country)), 
                           y = 1), 
             sides = "top")

在此处输入图片说明

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