R ggplotly dublicated legend - r

I try to generate a plot on which every point stands for an event. Color, Size and faced_grid are used to give additional information available in a visual way. The graph is working in ggplot2 but it is often important to know the exact numbers so an interactive version is needed which enables to hover over the point and get the info. I tried to convert the plot into an interactive version with the function ggplotly from the plotly-package. The problem then is, that the legend not only display the different states of the used attributes, it contains every existent combination. In addition, it did not display info from geom_rect.
I found related/similar questions but they used the function plot_ly and not ggploty or did not provide an answer.
Following, the same problem illustrated with the mtcars dataset:
library(plotly)
g = ggplot(mtcars,aes(x=mpg,y=disp,color = as.factor(cyl),size =as.factor(gear))) +
geom_point() +
geom_text(label = c(rep("A",nrow(mtcars)-5),rep("B",5)),color = "black",size=4) +
geom_rect(data=data.frame(name="zone",Start=20,End = 30,ymin = -Inf,ymax = Inf),aes(xmin=Start, xmax=End, ymin=ymin, ymax=ymax,fill=name),inherit.aes = FALSE,alpha=0.3)+
facet_grid(vs~am)
g
This is the result and how it should look like: ggplot Graph
Now using ggplotly
ggplotly(g)
This is the result: ggploty Graph
(1) The legend is now a combination of the different attributes used for Color and Size
(2) geom_rect is in the legend but didn’t get displayed in the graph
Does anyone knows how to get the same graph in ggplotly like in ggplot2? I am grateful for every hint. Thanks
Dave

I do not know how to fix the combination of legends when you use ggplotly. But, I can fix the second problem, if you do not use the Inf and -Inf, the geom_rect will work:
ggplotly(ggplot(mtcars,aes(x=mpg,y=disp, = as.factor(cyl),size =as.factor(gear))) +
geom_rect(aes( xmin=20,
xmax=30,
ymin=0,
ymax=max(mtcars$disp),
fill="Name"),
inherit.aes = FALSE, alpha=0.3) +
geom_point() +
geom_text(label = c(rep("A",nrow(mtcars)-5),rep("B",5)), = "black",size=4) +
facet_grid(vs~am))
However, the legends are bad.
I would suggest using subplot to create the same thing in Plotly, and I think this link Ben mentioned will help you create each subplot. One thing to mention is that I had trouble Illustrating different size in legend in plotly, while the size of the marker will be different, there will not be a legend for the size scale. Maybe a scale will be a better option.

Related

how to change the color scale for each graph with facet_wrap and legend

I have a question about facet_wrap() in ggplot2.
I am trying to make a graph that looks like this. I attach an example image 1.enter image description here
In image 1 it can be seen that there are two maps and each one has its legend and color scale. I would like to be able to do this with ggplot and the facet_wrap() function.
My problem is that because the data in the dataframe is very different, they have a lot of amplitude for each map, when plotting the scale it does not allow me to visualize it the way I want.
enter image description here
ggplot(dataframe,mapping=aes(x=lon,x=lat))+
geom_contour_fill((aes(z=hgt,fill=stat(level)))+
geom_contour(aes(z=hgt),color="black",size=0.2)+
scale_fill_distiller(palette = "YlOrBr",direction = 1,super=ScaleDiscretised)+
mi_mapa+
coord_quickmap(xlim = range(dataframe$lon),ylim=range(dataframe$lat),expand = FALSE)+
facet_wrap(~nombre_nivel,scales="free", ncol =2) +
labs(x="Longitud",y="Latitud",fill="altura",title = "campos")
my dataframe has a shape like this. Where the facets are determined by the level variable. In this case the dataframe has another variable which is temp instead of hgt, but it's just another name.
enter image description here
Thanks
I think I've faced the alike problem building the two parts of the single map with two different scales. I found the package grid useful.
library(grid)
grid.newpage()
print(myggplot, vp = specifiedviewport)
In my case I built the first p <- ggplot() than adjusted p2 <- p + ...
with printing the two ggplots (p and p2) in two viewports. You can newly construct p2 with individual scale and print it in the grid. You can find useful information
here.

Colour indication in the R plot

Trying to add some note at the bottom of R plot graph, to show what colour and line type has been used in the graph that represents for. Tried use mtext() function, but that only allow me to add text, not the line type. Any way to add those colour note?
Try this approach. Please next time follow the advice of #AllanCameron. There are plenty of people wanting to help you, but we need to analyse your data to discover the issue. Here I have used some dummy data similar to that showed in the plot. Next an approach for your issue. If you want a description of your data series you can add a legend. This can be done also using ggplot2 which is used in actual code:
library(ggplot2)
#Data
df <- data.frame(Year=2000:2009,
Positive=runif(10,0,1),
Negative=runif(10,-1,0),
Average=cumsum(seq(-0.5,1,length.out = 10)))
#Plot
ggplot(df,aes(x=factor(Year),y=Positive))+
geom_line(aes(y=Average,group=1,color='Average'),size=1)+
geom_bar(stat='identity',color='black',aes(fill='Positive'),show.legend = T)+
geom_bar(aes(y=Negative,fill='Negative'),stat='identity',color='black')+
scale_fill_manual("",values=c('red','blue','white'))+
scale_color_manual("",values = 'black')+
theme_bw()+
theme(legend.position = 'bottom',legend.key.height = unit(0.001,'mm'))+
xlab('Year')+labs(caption = 'Your Info')
Output:
You can play around key size to make it thinner.

Change contour colours using directlabels

I'm fairly new to ggplot2, and I'm trying to create a contour plot of data that has missing values. Because there's missing values I can't have the contours by themselves, so I'm combining a tiles background with a contour. The problem is the labels are the same colour as the background.
Suppose I have data like so:
DF1 <- data.frame(x=rep(1:3,3),y=rep(1:3,each=3),z=c(1,2,3,2,3,4,3,NA,NA))
I can make a plot like this:
require(ggplot2); require(directlabels)
plotDF <- ggplot(DF1,aes(x,y,z=z)) + geom_tile(aes(fill=z)) + stat_contour(aes(x,y,z=z,colour= ..level..),colour="white")
direct.label(plotDF)
This gives me a plot similar to what I want but I'd like to be able to change the colours of the labels to be black. Any ideas?
I spotted a similar post and thought this would be easy, something along the lines of direct.label(p, list("last.points", colour = "black"). I could not make it work, unfortunately; I believe, this is not directly supproted.
I then decided to use black magic and managed to do the trick by manually overriding the colour scale:
direct.label(plotDF +
scale_colour_gradient(low="black", high="black"))

How do i make a color spectrum legend which represents my z values?

I have managed to use the grey scale command to make a 3D scatter plot with the third dimension representing a color gradient. I have hit a wall when trying to produce the legend that coincides with it though. I already have the range of colors I want I just dont know how to tell R to make them into a legend. Here is my code.
conocarp.stands<-c(264,330,400,594,600,700,726,730,800,825,825,826,1914,2145,2200,2310,2475,2640,3630,3960,3960,4124,4554,5082,8250,8475,9200,1000)
fimb.size<-c(540,2160,1100,1170,350,850,2340,600,200,738,1080,1300,2416,540,3565,810,648,0,900,0,635,1210,0,900,2340,1152,0,0)
sugar.visits.cono<-c(0.005682,0,0.065,0,0,0.010714,0,0.010274,0.011875,0,0,0,0,0,0.007045,0,0.001414,0.002273,0,0.014141,0.001263,0.006426,0.000769,0.000295,0.005515,0.000186,0.00359,0.004939)
colors <- rev(grey(1:101/101))
zcolor <- colors[round((sugar.visits.cono -min(sugar.visits.cono))/diff(range(sugar.visits.cono))*100 + 1)]
plot(conocarp.stands,fimb.size, pch=1, cex=1.8,ann=FALSE)
points(conocarp.stands,fimb.size,col=zcolor, pch=16, cex=1.5)
zcolor is my z axis values and should be able to be used to produce my legend. I have tried working with various packages i.e. SDMTools and fields but I shouldnt need to go that rout.
Try this,
library(ggplot2)
d = data.frame(conocarp.stands = conocarp.stands,
fimb.size = fimb.size,
sugar.visits.cono = sugar.visits.cono)
ggplot(data = d, mapping = aes(x = conocarp.stands, y = fimb.size)) +
geom_point(aes(colour = sugar.visits.cono), shape = 19)
last_plot() + scale_colour_gradient(high="grey10", low="grey90") + theme_bw()
using the raster.grid command I found you could also solve this question, however i could not figure out how to label the axis. Thank you so much Baptiste I have been avoiding the ggplots 2 package but i think it is time i dove in. Here is my code using raster.grid if it helps anyone:
library(grid)
grid.raster(1:101/101,width=.075,height=.1)

Customize Contour Labels in ggplot2

I'm relatively new to ggplot2, and I'm having trouble adding appropriate labels to my contours. I would love to be able to add the labels without the directlabels package, but I haven't found a way to, so if you know of a way to customize labels without directlabels, I would love to here it.
Using the classic volcano example, I can add labels to the default contour plot using the directlabels packet in the following way:
library(plyr)
library(ggplot2)
library(directlabels)
library(reshape)
volcano<-melt(volcano)
v<-ggplot(volcano, aes(x,y,z=z))
e<-v + stat_contour(aes(colour=..level..))
direct.label(e)
In the above example, the labels are added appropriately, but things become more complicated if I try to specify my own break points for the contours:
e<-v + stat_contour(aes(breaks=c(160, 170, 180), colour=..level..))
direct.label(e)
Now, the contours are specified by the breaks I have provided, but labels still appear for all of the default contours. How do I only plot only labels for the graphed contours?
A related issue, how would I plot labels for contour levels not included in the default? Say a break of 165:
e<-v + stat_contour(aes(breaks=c(165), colour=..level..))
direct.label(e)
Thanks for any help!
The current development version (directlabels_2013.6.15 with ggplot2_0.9.3.1) should fix your problem (as the author of the directlabels package explained to me). You can install it with:
install.packages("directlabels", repos="http://r-forge.r-project.org")
And then:
library(plyr)
library(ggplot2)
library(directlabels)
library(reshape)
volcano<-melt(volcano)
v<-ggplot(volcano, aes(X1,X2,z=value))
e<-v + stat_contour(aes(colour=..level..), breaks=c(165))
direct.label(e)
I noted several other limitations with simple workarounds:
the first ggplot call must contain the z aesthetic
this works only with the stat_contour (and not with the geom_contour)
the colour aesthetic must be defined in the stat_contour call and set to ..level..
Finally, if you want to control the label and contour line colours (black labels and blue contour lines for instance), you can achieved this as follow:
e<-v + stat_contour(aes(colour=..level..), colour = "blue", breaks=c(165))
e<-e + scale_colour_continuous(low = "#FF0000", high = "#FF0000")
direct.label(e)

Resources