Frage

i have a bar chart with two groups, where y-axis = dollars earned & the width of the x-axis = # units sold. Sample data below:

test<- structure(list(Person = c("Bob", "Bob", "Bob", "Bob", "Bob", 
"Jim", "Jim", "Jim", "Jim", "Jim"), Car = c("Wombat", "Beetle", 
"Impala", "Carrera", "Sienna", "Wombat", "Beetle", "Impala", 
"Carrera", "Sienna"), tot = c(75090, 229994, 1229347, 247052, 
1148873, 41114, 2430, 430423, 629812, 30442), freq = c(5L, 620L, 
1324L, 219L, 550L, 36L, 1L, 213L, 195L, 2L)), .Names = c("Person", 
"Car", "tot", "freq"), row.names = c(NA, 10L), class = "data.frame")

# Print bar chart.
ggplot()+
geom_bar(data=test,aes(x=reorder(Car,tot,function(x) -sum(x)),
                       y=as.numeric(tot)/1000,width=freq/1000,fill=Person),
       stat='identity',position='identity')

I want to do the following two things to this chart, but am hitting roadblocks:

A) For each Car category, I want the Persons arranged next to one another, not on top of one another. ggplot says I can't position = 'dodge' for widths of varying lengths.

B) It seems that the spacing between Car categories is set based on the bar with the largest width. Is it possible to make that spacing vary in a manner such as width * .05? For instance, I want a narrower space between the Sienna, Carrera, & Beetle.

War es hilfreich?

Lösung

It's probably a better idea to split these charts. First, all your problems will be solved by themselves. Second, you won't mix different variables (units sold and car category in your example) on the same axis, thus avoiding a bad practice.

If you insist on plotting things your way, well, there is no quick way I can think of: ggplot discourages its "unconventional" usage. Here's the most famous example: Plot with 2 y axes, one y axis on the left, and another y axis on the right

library(gridExtra)
p1 <- ggplot()+
    geom_bar(data=test,aes(x=reorder(Car,tot,function(x) -sum(x)),
                           y=tot/1000,fill=Person),
             stat='identity',position='dodge')
p2 <- ggplot()+
    geom_bar(data=test,aes(x=reorder(Car,tot,function(x) -sum(x)),
                           y=freq/1000,fill=Person),
             stat='identity',position='dodge')
grid.arrange(p1, p2)

enter image description here

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top