geom_polygon in ggplot2
Examples of geom_polygon in R.
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.
Basic Ploygon
library(plotly)
ids <- factor(c("1.1", "2.1", "1.2", "2.2", "1.3", "2.3"))
values <- data.frame(
id = ids,
value = c(3, 3.1, 3.1, 3.2, 3.15, 3.5)
)
positions <- data.frame(
id = rep(ids, each = 4),
x = c(2, 1, 1.1, 2.2, 1, 0, 0.3, 1.1, 2.2, 1.1, 1.2, 2.5, 1.1, 0.3,
0.5, 1.2, 2.5, 1.2, 1.3, 2.7, 1.2, 0.5, 0.6, 1.3),
y = c(-0.5, 0, 1, 0.5, 0, 0.5, 1.5, 1, 0.5, 1, 2.1, 1.7, 1, 1.5,
2.2, 2.1, 1.7, 2.1, 3.2, 2.8, 2.1, 2.2, 3.3, 3.2)
)
datapoly <- merge(values, positions, by=c("id"))
p <- ggplot(datapoly, aes(x=x, y=y)) + geom_polygon(aes(fill=value, group=id))
fig <- ggplotly(p)
fig
Inspired by ggplot2 docs
Ellipses
# create data
set.seed(20130226)
n <- 200
x1 <- rnorm(n, mean = 2)
y1 <- 1.5 + 0.4 * x1 + rnorm(n)
x2 <- rnorm(n, mean = -1)
y2 <- 3.5 - 1.2 * x2 + rnorm(n)
class <- rep(c("A", "B"), each = n)
df <- data.frame(x = c(x1, x2), y = c(y1, y2), colour = class)
# get code for "stat_ellipse"
library(devtools)
library(ggplot2)
library(proto) #source_url("https://raw.github.com/JoFrhwld/FAAV/master/r/stat-ellipse.R")
p <- qplot(data = df, x = x, y = y, colour = class) +
stat_ellipse(geom = "polygon", alpha = 1/2, aes(fill = class))
fig <- ggplotly(p)
fig
Highlighting
library(plotly)
tmp <- with(mtcars, data.frame(x=c(0, 0, max(wt)*35), y=c(0, max(wt), max(wt))))
p <- ggplot(mtcars, aes(hp, wt)) +
geom_polygon(data=tmp, aes(x, y), fill="#d8161688") +
geom_point()
fig <- ggplotly(p)
fig
Inspired by Stack Overflow
Vertical Conversion
library(plotly)
library(data.table)
df<-data.table(Product=letters[1:10], minX=1:10, maxX=5:14, minY= 10:1, maxY=14:5)
df.t<-data.table(rbind( df[,list(Product,X=minX,Y=minY)],
df[,list(Product,X=minX,Y=maxY)],
df[,list(Product,X=maxX,Y=minY)],
df[,list(Product,X=maxX,Y=maxY)]))[
order(Product,X,Y)]
p <- ggplot(df,aes(xmin=minX,xmax=maxX,ymin=minY,ymax=maxY,fill=Product))+
geom_rect()
fig <- ggplotly(p)
fig
Inspired by Stack Overflow
Distributions
library(plotly)
x=seq(-2,2,length=200)
dat <- data.frame(
norm = dnorm(x,mean=0,sd=0.2),
logistic = dlogis(x,location=0,scale=0.2), x = x
)
p <- ggplot(data=dat, aes(x=x)) +
geom_polygon(aes(y=norm), fill="red", alpha=0.6) +
geom_polygon(aes(y=logistic), fill="blue", alpha=0.6) +
xlab("z") + ylab("") +
scale_x_continuous(expand = c(0, 0)) +
scale_y_continuous(expand = c(0, 0))
fig <- ggplotly(p)
fig
Inspired by Stack Overflow
Convex Hull
library(plotly)
library(RColorBrewer)
# Generate some data
nn <- 500
myData <- data.frame(X = rnorm(nn),
Y = rnorm(nn))
setK = 6 # How many clusters?
clusterSolution <- kmeans(myData, centers = setK)
myData$whichCluster <- factor(clusterSolution$cluster)
splitData <- split(myData, myData$whichCluster)
appliedData <- lapply(splitData, function(df){
df[chull(df), ] # chull really is useful, even outside of contrived examples.
})
combinedData <- do.call(rbind, appliedData)
zp3 <- ggplot(data = myData,
aes(x = X, y = Y))
zp3 <- zp3 + geom_polygon(data = combinedData, # This is also a nice example of how to plot
aes(x = X, y = Y, fill = whichCluster), # two superimposed geoms
alpha = 1/2) # from different data.frames
zp3 <- zp3 + geom_point(size=1)
zp3 <- zp3 + coord_equal()
zp3 <- zp3 + scale_fill_manual(values = colorRampPalette(rev(brewer.pal(11, "Spectral")))(setK))
fig <- ggplotly(zp3)
fig
Inspired by is.R()
County-Level Boundaries
library(plotly)
library(maps)
county_df <- map_data("county")
state_df <- map_data("state")
# create state boundaries
p <- ggplot(county_df, aes(long, lat, group = group)) +
geom_polygon(colour = alpha("black", 1/2), fill = NA) +
geom_polygon(data = state_df, colour = "black", fill = NA) +
theme_void()
fig <- ggplotly(p)
fig
County-Level Choropleths
library(plotly)
library(dplyr)
library(maps)
# map data
county_df <- map_data("county")
state_df <- map_data("state")
county_df$subregion <- gsub(" ", "", county_df$subregion)
#election data
df <- read.csv("https://raw.githubusercontent.com/bcdunbar/datasets/master/votes.csv")
df <- subset(df, select = c(Obama, Romney, area_name))
df$area_name <- tolower(df$area_name)
df$area_name <- gsub(" county", "", df$area_name)
df$area_name <- gsub(" ", "", df$area_name)
df$area_name <- gsub("[.]", "", df$area_name)
df$Obama <- df$Obama*100
df$Romney <- df$Romney*100
for (i in 1:length(df[,1])) {
if (df$Obama[i] > df$Romney[i]) {
df$Percent[i] = df$Obama[i]
} else {
df$Percent[i] = -df$Romney[i]
}
}
names(df) <- c("Obama", "Romney", "subregion", "Percent")
# join data
US <- inner_join(county_df, df, by = "subregion")
US <- US[!duplicated(US$order), ]
# colorramp
blue <- colorRampPalette(c("navy","royalblue","lightskyblue"))(200)
red <- colorRampPalette(c("mistyrose", "red2","darkred"))(200)
#plot
p <- ggplot(US, aes(long, lat, group = group)) +
geom_polygon(aes(fill = Percent),
colour = alpha("white", 1/2), size = 0.05) +
geom_polygon(data = state_df, colour = "white", fill = NA) +
ggtitle("2012 US Election") +
scale_fill_gradientn(colours=c(blue,"white", red)) +
theme_void()
fig <- ggplotly(p)
fig
What About Dash?
Dash for R is an open-source framework for building analytical applications, with no Javascript required, and it is tightly integrated with the Plotly graphing library.
Learn about how to install Dash for R at https://dashr.plot.ly/installation.
Everywhere in this page that you see fig
, you can display the same figure in a Dash for R application by passing it to the figure
argument of the Graph
component from the built-in dashCoreComponents
package like this:
library(plotly)
fig <- plot_ly()
# fig <- fig %>% add_trace( ... )
# fig <- fig %>% layout( ... )
library(dash)
library(dashCoreComponents)
library(dashHtmlComponents)
app <- Dash$new()
app$layout(
htmlDiv(
list(
dccGraph(figure=fig)
)
)
)
app$run_server(debug=TRUE, dev_tools_hot_reload=FALSE)