Trying to combine a geom_sf() with some other geoms. I need to reverse the y-axis for the plot to appear correctly. However, geom_sf() seems to ignore scale_y_reverse().
Example:
# install the dev version of ggplot2
devtools::install_github("tidyverse/ggplot2")
library(ggplot2)
library(sf)
library(rgeos)
library(sp)
# make triangle
tmpdf <- data.frame(id = 1,
geom = c("LINESTRING(10 10,-10 10,0 0,10 10)"), stringsAsFactors = F)
# read WKT polygons into 'sp' SpatialPolygons object
tmpdf$spgeom <- lapply(tmpdf$geom, FUN = function(x) readWKT(x))
# extract coordinates from the linestring (there has got to be a better way to do this...)
test <- tmpdf[1,"spgeom"]
test2 <- sapply(test, FUN=function(x) x#lines)
test3 <- sapply(test2, FUN=function(x) x#Lines)
test4 <- lapply(test3, FUN=function(x) x#coords)
# plot the sp coordinates
ggplot() +
geom_point(data=data.frame(test4[[1]]), aes(x,y), color="blue") +
geom_path(data=data.frame(test4[[1]]), aes(x=x, y=y), color="blue") +
coord_fixed()
# make an 'sf' sfc_POLYGON object
tmpdf$sfgeom <- st_as_sfc(tmpdf$geom)
## plot both together, they overlap
ggplot() +
geom_point(data=data.frame(test4[[1]]), aes(x,y), color="blue") +
geom_path(data=data.frame(test4[[1]]), aes(x=x, y=y), color="blue") +
coord_fixed() +
geom_sf(data=tmpdf, aes(geometry=sfgeom), color="red")
plot outputs with warning:
Coordinate system already present. Adding new coordinate system, which
will replace the existing one.
## plot with scale reverse, and everything but the geom_sf flips.
ggplot() +
geom_point(data=data.frame(test4[[1]]), aes(x,y), color="blue") +
geom_path(data=data.frame(test4[[1]]), aes(x=x, y=y), color="blue") +
coord_fixed() +
geom_sf(data=tmpdf, aes(geometry=sfgeom), color="red") +
scale_y_reverse()
plot outputs with warning:
Coordinate system already present. Adding new coordinate system, which
will replace the existing one.
Suggestions for getting the geom_sf y coordinates reversed?
I tried this:
coord_sf(ylim=-(range(st_coordinates(tmpdf$sfgeom)[,"Y"])))
and all that did was change the axis, not the actual geoms.
Aha! Here's a workaround:
## get the geom coordinates as data.frame
geomdf <- st_coordinates(tmpdf$sfgeom)
## reverse Y coords
geomdf[,"Y"] <- geomdf[,"Y"]*-1
## re-create geom
tmpdf$sfgeom2 <- st_as_sfc(st_as_text(st_linestring(geomdf)))
## plot the reversed y-coordinate geom:
ggplot() +
geom_point(data=data.frame(test4[[1]]), aes(x,y), color="blue") +
geom_path(data=data.frame(test4[[1]]), aes(x=x, y=y), color="blue") +
coord_fixed() +
geom_sf(data=tmpdf, aes(geometry=sfgeom2), color="red") +
scale_y_reverse()
Related
I'm having some problems in converting a ggplot in to a plotly object, and retaining the same legend attributes. What I want:
For grouped series, a single line for fit, and faded region for ribbon of same colour, with transparency
No lines at the edge of the ribbon
Grouped legends for the lines, points and ribbons
Here is the code showing the 2 approaches I tried based on this answer:
ggplot: remove lines at ribbon edges
Both have an undesirable effect as you can see when running. Any suggestions would be great :)
library(plotly)
library(ggplot2)
# fake data
set.seed(1)
dt <- data.frame(x=rep(1:7,2), group=rep(letters[1:2], each=7), value=runif(14))
dt$lwr <- dt$value*.9
dt$upr <- dt$value*1.1
# build plot in ggplot, don't want lines at the edge
pl <- ggplot(data=dt, aes(y=value, x=x, group=group, colour=group,
fill=group)) +
geom_point() +
geom_line() +
geom_ribbon(aes(ymin=lwr, ymax=upr), alpha=.3, linetype=0) +
theme_minimal()
# looks ok, no lines at the edges
pl
# lines at edges, single group
ggplotly(pl)
# alternative: try reverting colour to NA
pl2 <- ggplot(data=dt, aes(y=value, x=x, group=group, colour=group,
fill=group)) +
geom_point() +
geom_line() +
geom_ribbon(aes(ymin=lwr, ymax=upr), alpha=.3, colour=NA) +
theme_minimal()
# looks ok
pl2
# no lines, but now not grouped, and some weird naming
ggplotly(pl2)
Thanks, Jonny
EDIT:
Addition to the accepted answer, in functional form
# dd: ggplotly object
library(stringi)
library(rvest)
remove_ggplotly_ribbon_lines <- function(dd){
find <- rvest::pluck(dd$x$data, "fillcolor")
w <- which(!sapply(find, is.null))
for(i in w){
dd$x$data[[i]]$line$color <-
stringi::stri_replace_all_regex(dd$x$data[[i]]$line$color, ",[\\d.]*\\)$", ",0.0)")
}
return(dd)
}
remove_ggplotly_ribbon_lines(ggplotly(pl))
Hi this is more a comment than an answer but I do not have right to post comments.
If you investigate the ggplotly object you will see that it is actually just a list. Changing the right elements of the list helps in controlling plot options.
The solution below just changes the alpha of the lines at ribbon edges. Hope this helps
library(plotly)
set.seed(1)
dt <- data.frame(x=rep(1:7,2), group=rep(letters[1:2], each=7), value=runif(14))
dt$lwr <- dt$value*.9
dt$upr <- dt$value*1.1
# build plot in ggplot, don't want lines at the edge
pl <- ggplot(data=dt, aes(y=value, x=x, group=group, colour=group,
fill=group)) +
geom_point() +
geom_line() +
geom_ribbon(aes(ymin=lwr, ymax=upr), alpha=.3, linetype=0) +
theme_minimal()
# looks ok, no lines at the edges
pl
# no lines at edges
dd = ggplotly(pl)
dd$x$data[[3]]$line$color = "rgba(248,118,109,0.0)"
dd$x$data[[4]]$line$color = "rgba(0,191,196,0.0)"
dd
How I can modify the following code to have a plot between x and y (scatter plot) and the fitted values X0.025 and y=X0.975 as the curves (lines) on the plot. (please run plot(m6) to see the plot which I am looking for to make by ggplot)
library(quantregGrowth)
data(growthData)
m6<-gcrq(y~ps(x, lambda=seq(0,100,l=20)), tau=c(0.025,0.975), n.boot=10,
data=growthData)
plot(m6)
I tried to make this plot by ggplot and here is the code:
library(ggplot2)
library(plotly)
temp <- data.frame(m6$fitted)
growthData_b <- cbind(growthData, temp)
a <- ggplot(data=growthData_b, aes(x, y=X0.025)) + geom_line() +
geom_line(data=growthData_b, aes(x, y=X0.975), color = "red") + theme_bw()
Are you looking for this?
ggplot(data=growthData_b, aes(x, y=X0.025)) +
geom_line() +
geom_line(data=growthData_b, aes(x, y=X0.975), color = "red", linetype = 2) +
theme_bw() +
geom_point(aes(x=x, y=y), shape = 1)
I have done a clustering dendrogram following a previous code I found online, but the x-axis of is not being shown in the graph. I would like to have the dissimilarity value shown in the x-axis, but I have not been successful.
females<-cervidae[cervidae$Sex=="female",]
dstf <- daisy(females[,9:14], metric = "euclidean", stand = FALSE)
hcaf <- hclust(dstf, method = "ave")
k <- 3
clustf <- cutree(hcaf,k=k) # k clusters
dendrf <- dendro_data(hcaf, type="rectangle") # convert for ggplot
clust.dff <- data.frame(label=rownames(females), cluster=factor(clustf),
females$Genus, females$Species)
dendrf[["labels"]] <- merge(dendrf[["labels"]],clust.dff, by="label")
rectf <- aggregate(x~cluster,label(dendrf),range)
rectf <- data.frame(rectf$cluster,rectf$x)
ymax <- mean(hcaf$height[length(hcaf$height)-((k-2):(k-1))])
fem=ggplot() +
geom_segment(data=segment(dendrf), aes(x=x, y=y, xend=xend, yend=yend)) +
geom_text(data=label(dendrf), aes(x, y, label= females.Genus, hjust=0,
color=females.Genus),
size=3) +
geom_rect(data=rectf, aes(xmin=X1-.3, xmax=X2+.3, ymin=0, ymax=ymax),
color="red", fill=NA)+
coord_flip() + scale_y_reverse(expand=c(0.2, 0)) +
theme_dendro() + scale_color_discrete(name="Genus") +
theme(legend.position="none")
Here is how my dendrogram looks:
Your code included theme_dendro(), which is described in its help file as:
Sets most of the ggplot options to blank, by returning blank theme
elements for the panel grid, panel background, axis title, axis text,
axis line and axis ticks.
You force the x-axis line / text / ticks to be visible in theme():
ggplot() +
geom_segment(data=segment(dendrf), aes(x=x, y=y, xend=xend, yend=yend)) +
geom_text(data=label(dendrf), aes(x, y, label= label, hjust=0,
color=cluster),
size=3) +
geom_rect(data=rectf, aes(xmin=X1-.3, xmax=X2+.3, ymin=0, ymax=ymax),
color="red", fill=NA)+
coord_flip() +
scale_y_reverse(expand=c(0.2, 0)) +
theme_dendro() +
scale_color_discrete(name="Cluster") +
theme(legend.position="none",
axis.text.x = element_text(), # show x-axis labels
axis.ticks.x = element_line(), # show x-axis tick marks
axis.line.x = element_line()) # show x-axis lines
(This demonstration uses a built-in dataset, since I'm not sure what's cervidae. Code used to create this is reproduced below:)
library(cluster); library(ggdendro); library(ggplot2)
hcaf <- hclust(dist(USArrests), "ave")
k <- 3
clustf <- cutree(hcaf,k=k) # k clusters
dendrf <- dendro_data(hcaf, type="rectangle") # convert for ggplot
clust.dff <- data.frame(label=rownames(USArrests),
cluster=factor(clustf))
dendrf[["labels"]] <- merge(dendrf[["labels"]],clust.dff, by="label")
rectf <- aggregate(x~cluster,label(dendrf),range)
rectf <- data.frame(rectf$cluster,rectf$x)
ymax <- mean(hcaf$height[length(hcaf$height)-((k-2):(k-1))])
I want to make a plot in ggplot2 like this
x <- 1:10
y <- rnorm(10) + x
df <- data.frame(x=x,y=y)
plot(x,y)
lines(x,y,type='c')
I like this type='c' style,R help tell me
"c" for empty points joined by lines
but how can I implement this type in ggplot2?
library(ggplot2)
ggplot(data=df,aes(x=x,y=y)) + geom_line() + geom_point(shape=21,size=3)
I mean, how to make a blank between the empty points and the lines? which linetype should I choose?
thank you very much
ggplot(data=df,aes(x=x,y=y)) +
geom_line() +
geom_point(shape=21, size=5, colour="white", fill="white") +
geom_point(shape=21,size=3) +
theme_bw()
I start by giving you my example code:
x <- runif(1000,0, 5)
y <- c(runif(500, 0, 2), runif(500, 3,5))
A <- data.frame("X"=x,"Y"=y[1:500])
B <- data.frame("X"=x,"Y"=y[501:1000])
ggplot() +
stat_bin_hex(data=A, aes(x=X, y=Y), bins=10) +
stat_bin_hex(data=B, aes(x=X, y=Y), bins=10) +
scale_fill_continuous(low="red4", high="#ED1A3A")
It produces the following plot:
Now I want the lower hexagons to follow a different scale. Namely ranging from a dark green to a lighter green. How can I achieve that?
Update:
As you can see from the answers so far, I am asking myself whether there is a solution without using alpha scales. Also, using two plots with no margin or something similar is not an option for my specific application. Though they both are legitimate answers :)
Rather than trying to get two different fill scales in one plot you could alter the colours of the lower values, after the plot has been built. The basic idea is have two plots with the differing fill scales and then copy accross certain details from one plot to the other.
# Base plot
p <- ggplot() +
stat_bin_hex(data=A, aes(x=X, y=Y), bins=10) +
stat_bin_hex(data=B, aes(x=X, y=Y), bins=10)
# Produce two plots with different fill colours
p1 <- p + scale_fill_continuous(low="red4", high="#ED1A3A")
p2 <- p + scale_fill_continuous(low="darkgreen", high="lightgreen")
# Get fill colours for second plot and overwrite the corresponding
# values in the first plot
g1 <- ggplot_build(p1)
g2 <- ggplot_build(p2)
g1$data[[1]][,"fill"] <- g2$data[[1]][,"fill"]
# You can draw this now but there is only one legend
grid.draw(ggplot_gtable(g1))
To have two legends you can join the legends from the two plots together
# Bind the legends from the two plots together
g1 <- ggplot_gtable(g1)
g2 <- ggplot_gtable(g2)
g1$grobs[[grep("guide", g1$layout$name )]] <-
rbind(g1$grobs[[grep("guide", g1$layout$name )]],
g2$grobs[[grep("guide", g2$layout$name )]] )
grid.newpage()
grid.draw(g1)
Giving (from set.seed(10) prior to data generation)
This should provide more or less what you want
ggplot() +
stat_bin_hex(data=A, aes(x=X, y=Y, alpha=..count..), bins=10,fill="green") +
stat_bin_hex(data=B, aes(x=X, y=Y, alpha=..count..), bins=10,fill="red")
To avoid that the grey is disturbing due to the alpha one could underlay the plot with another white plot at the same location and darken the colours a bit, as suggested by the TO in the comments
#just the red to show the impact due to scale_alpha
ggplot() +scale_alpha_continuous(range=c(0.5,1))+ stat_bin_hex(data=A, aes(x=X, y=Y), bins=10,fill="white",show.legend = TRUE) +
+ stat_bin_hex(data=A, aes(x=X, y=Y, alpha=..count..), bins=10,fill="red",show.legend = TRUE) +
+ stat_bin_hex(data=B, aes(x=X, y=Y, alpha=..count..), bins=10,fill="green", show.legend=TRUE)+guides(fill=FALSE, alpha=FALSE)
An alternative, if you want more options to play with the colours, just create two plots and remove all the space between the two plots when combined with grid.arrange().
p1 <- ggplot() + stat_bin_hex(data=B, aes(x=X, y=Y), bins=10) +
scale_fill_continuous(low="red4", high="#ED1A3A") + xlab("") + theme(axis.text.x=element_blank(), axis.ticks.x=element_blank(), plot.margin=unit(c(1,1,-0.5,1), "cm")) + scale_y_continuous(limits = c(2.5, 5.5))
p2 <- ggplot() + stat_bin_hex(data=A, aes(x=X, y=Y), bins=10) + scale_fill_continuous(low="darkgreen", high="green") + theme(plot.margin=unit(c(-0.5,1,1,1), "cm")) + scale_y_continuous(limits = c(-0.5, 2.5))
grid.arrange(p1,p2)