Violin Plots in ggplot2
How to make Violin Plots in ggplot2 with Plotly.
New to Plotly?
Plotly is a free and open-source graphing library for R. We recommend you read our Getting Started guide for the latest installation or upgrade instructions, then move on to our Plotly Fundamentals tutorials or dive straight in to some Basic Charts tutorials.
Default violin plot
library(plotly)
library(ggplot2)
p <- ggplot(mtcars, aes(factor(cyl), mpg))
p <- p + geom_violin()
plotly::ggplotly(p)
Flip plot orientation
library(plotly)
library(ggplot2)
p <-
ggplot(mtcars, aes(mpg, factor(cyl))) +
geom_violin()
plotly::ggplotly(p)
With geom_violin()
, the y-axis must always be the continuous variable, and the x-axis the categorical variable. To create horizontal violin graphs, keep the x- and y-variables as is and add coord_flip()
.
library(plotly)
library(ggplot2)
district_density <- read.csv("https://raw.githubusercontent.com/plotly/datasets/master/district_density.csv", stringsAsFactors = FALSE)
district_density$cluster <- factor(district_density$cluster, levels=c("Pure urban", "Urban-suburban mix", "Dense suburban", "Sparse suburban", "Rural-suburban mix", "Pure rural"))
district_density$region <- factor(district_density$region, levels=c("West", "South", "Midwest", "Northeast"))
p <- ggplot(district_density,aes(x=cluster, y=dem_margin, fill=cluster)) +
geom_violin(colour=NA) +
geom_hline(yintercept=0, alpha=0.5) +
labs(title = "Democratic performance in the 2018 House elections, by region and density",
x = "Density Index\nfrom CityLab",
y = "Margin of Victory/Defeat") +
coord_flip()
ggplotly(p)