Reputation: 115
I made many tries but could not make this labels be dodged:
Sistema<-c("MOTOR EQUIPO MOVIL","PMs","SISTEMA HIDRAULICO","TREN DE POTENCIA","CABINA","SISTEMA ELECTRICO 24V","SISTEMA CHASIS","SISTEMA DE FRENOS","VARIOS DISPATCH","SUSPENSION Y RUEDAS")
DetNP<-c(17,1,8,10,13,8,3,2,2,2)
DetP<-c(1,16,3,3,1,1,1,1,1,1)
Indisp<-c(0.0305,0.0203,0.0109,0.0094,0.0093,0.0069,0.0060,0.0020,0.0004,0.0003)
Total<-c(18,17,11,13,14,9,4,3,3,3)
Max<-c(17,16,8,10,13,8,1,2,2,2)
datos<-data.frame(Sistema,DetNP,DetP,Indisp,Total,Max)
library(ggplot2)
library(reshape2)
library(scales)
datos<- melt(datos, id = c("Sistema","Indisp","Total","Max"))
scaleFactor <- max(datos$value) / max(datos$Indisp)
ggplot(datos) +
geom_bar(aes(x = reorder(Sistema, -Indisp), y = value, fill = variable),stat = "identity", position = "dodge") +
geom_text(aes(x = reorder(Sistema, -Indisp), y = value/2, label = value), position = position_dodge(width = 0.9))
This is the result, (note: labels should be placed in the middle of the bars)
I tried modyfing position_dodge parameter, adding stat="Identity" and playing with size and other stuff but couldnt success. Any help would be welcomed.
Upvotes: 1
Views: 67
Reputation: 46888
You can use position_dodge2 (because you need to account for size of the bar):
ggplot(datos)+geom_bar(aes(x=reorder(Sistema,-Indisp), y=value,
fill=variable),stat="identity",position="dodge")+
geom_text(aes(x=reorder(Sistema,-Indisp),
y=value/2,label=value), position = position_dodge2(width=0.9))
Note, most likely you need to do something about your x-axis label..
Upvotes: 1
Reputation: 897
You were super close - The one big thing you were forgetting was to include some way of telling the geom_text
layer about the fill
argument (e.g. the dodged bar chart). I added this information into the geom_text
layer using the group
argument in aes
.
library(ggplot2)
library(reshape2)
library(scales)
datos<- melt(datos, id = c("Sistema","Indisp","Total","Max"))
scaleFactor <- max(datos$value) / max(datos$Indisp)
ggplot(datos) +
geom_bar(aes(x=reorder(Sistema,-Indisp), y=value, fill=variable),
stat="identity", position="dodge") +
geom_text(aes(x=reorder(Sistema,-Indisp), y=value/2, label=value, group = variable), #added in group=variable to geom_text
position = position_dodge(width = 0.9)) # experiment with the width value to get the spacing you want
Upvotes: 0