user85727
user85727

Reputation: 173

plotting labels outside of plot in ggplot

I have a plot made from the following code:

variable=c("A","B","C","D","E")   
value=c(1,2,3,4,5);
type=c("A","B","A","A","B")
temp<-data.frame(var=factor(variable),val=value,type=factor(type))
p<-ggplot(temp,aes(var,val,color=type))+geom_point(aes(colour="type"))
p<-p+coord_flip()+theme(plot.margin = unit(c(1,5,1,1), "lines"),legend.position = "none") 

myplot

How can I labels for the values (now on x-axis) of the plot on the right-side of the plot at the correct level (ie, i want it to say "5 4 3 2 1" vertically on the right side at the level (height) of the corresponding variable?

Thanks

Upvotes: 0

Views: 704

Answers (1)

Lucy
Lucy

Reputation: 991

if you make the "variable" the y-axis label rather than the actual values of the plot, you can use the sec_axis as a 1:1 transformation:

temp <- data.frame(val = value, var = value, type = type) 
p <- ggplot(temp,aes(var,val,color=type)) +
     geom_point(aes(colour="type")) +
     theme(plot.margin = unit(c(1,5,1,1), "lines"), legend.position = "none")
p <- p + scale_y_continuous(labels = variable, sec.axis = sec_axis(~.*1))
p

enter image description here

Upvotes: 1

Related Questions