r - ggplot version of dotplot -


curious how plot dotplot using ggplot or plotly library functions. label mpg values on individual dots.

# dotplot: grouped sorted , colored # sort mpg, group , color cylinder  x <- mtcars[order(mtcars$mpg),] # sort mpg x$cyl <- factor(x$cyl) # must factor x$color[x$cyl==4] <- "red" x$color[x$cyl==6] <- "blue" x$color[x$cyl==8] <- "darkgreen"     dotchart(x$mpg,labels=row.names(x),cex=.7,groups= x$cyl,          main="gas milage car models\ngrouped cylinder",          xlab="miles per gallon", gcolor="black", color=x$color) 

enter image description here

with quick clean of rownames column can following.

we used factor() aesthetics color becomes discrete/ when faceting acheive need specify "free_y" scale , space.

base

library(tidyverse) mtcars2 = rownames_to_column(mtcars, "car") ggplot(mtcars2, aes(x = mpg, y = factor(car), color = factor(cyl))) +    geom_point(shape = 1) +    facet_grid(cyl ~ ., scales = "free_y", space = "free_y") +    theme_bw() +    theme(panel.grid = element_blank(),         panel.grid.major.y = element_line(size=.1, color="grey90"),         legend.position = "none") +   ggtitle("gas milage car models\ngrouped cylinder") +    xlab("miles per gallon") +   ylab("") 

enter image description here


adding text

ggplot(mtcars2, aes(x = mpg, y = factor(car), color = factor(cyl))) +    geom_point(shape = 1) +    geom_text(aes(label = mpg), colour = "grey40", size = 3, hjust = -0.3) +    facet_grid(cyl ~ ., scales = "free_y", space = "free_y") +    theme_bw() +    theme(panel.grid = element_blank(),         panel.grid.major.y = element_line(size=.1, color="grey90"),         legend.position = "none") +   ggtitle("gas milage car models\ngrouped cylinder") +    xlab("miles per gallon") +   ylab("") 

enter image description here

you can use geom_label instead geom_text works great here.


Comments

Popular posts from this blog

ios - MKAnnotationView layer is not of expected type: MKLayer -

ZeroMQ on Windows, with Qt Creator -

unity3d - Unity SceneManager.LoadScene quits application -