2012-06-07 14 views
31

Estaba trabajando en hacer un diagrama de puntos horizontal (?) En ggplot2, y me hizo pensar en intentar crear una barra horizontal. Sin embargo, estoy encontrando algunas limitaciones para poder hacer esto.Barplot horizontal en ggplot2

Aquí es mis datos:

df <- data.frame(Seller=c("Ad","Rt","Ra","Mo","Ao","Do"), 
       Avg_Cost=c(5.30,3.72,2.91,2.64,1.17,1.10), Num=c(6:1)) 
df 
str(df) 

Inicialmente, me genera un gráfico de puntos con el siguiente código:

require(ggplot2) 
ggplot(df, aes(x=Avg_Cost, y=reorder(Seller,Num))) + 
    geom_point(colour="black",fill="lightgreen") + 
    opts(title="Avg Cost") + 
    ylab("Region") + xlab("") + ylab("") + xlim(c(0,7)) + 
    opts(plot.title = theme_text(face = "bold", size=15)) + 
    opts(axis.text.y = theme_text(family = "sans", face = "bold", size = 12)) + 
    opts(axis.text.x = theme_text(family = "sans", face = "bold", size = 12)) 

Sin embargo, ahora estoy tratando de crear un barplot horizontal y encontrar que yo soy incapaz de hacerlo Lo intenté coord_flip() y tampoco fue útil.

ggplot(df, aes(x=Avg_Cost, y=reorder(Seller,Num))) + 
    geom_bar(colour="black",fill="lightgreen") + 
    opts(title="Avg Cost") + 
    ylab("Region") + xlab("") + ylab("") + xlim(c(0,7)) + 
    opts(plot.title = theme_text(face = "bold", size=15)) + 
    opts(axis.text.y = theme_text(family = "sans", face = "bold", size = 12)) + 
    opts(axis.text.x = theme_text(family = "sans", face = "bold", size = 12)) 

¿Alguien puede proporcionar alguna ayuda sobre cómo generar un barplot horizontal en ggplot2?

Respuesta

80
ggplot(df, aes(x=reorder(Seller, Num), y=Avg_Cost)) + 
    geom_bar(stat='identity') + 
    coord_flip() 

Sin stat='identity' ggplot quiere agregar sus datos en el recuento.

+1

Cada 'geom' en ggplot2 tiene un' stat' predeterminado. Para 'geom_bar' la estadística por defecto es' bin', por lo tanto, debe cambiarse a 'identity' como lo mostró Justin. Los otros dos geoms que por defecto son bin son 'freqpoly' y por supuesto' histogram'. – Pete