I've looked through the description and the book on ggplot2 and cannot find a simple way of eliminating the legend in a simple density plot with a filled color.
Here is what I've tried with a simple sequence of 1000 numbers (plotseries) that had about 200
NA in the first 200 spots.
qplot(plotseries,geom="density",fill="red",na.rm=TRUE,show_guide=FALSE)
qplot(plotseries,geom="density",fill="red",na.rm=TRUE,legend.position="none")
I looked at the online ggplot2 doc and could not find anything there either....
If you just use the normal qplot command and then add + theme(legend.position = "none") to your code, it will remove the legend. So, your code will look as follows:
qplot(plotseries,geom="density",fill="red",na.rm=TRUE) + theme(legend.position="none")
Usually such things work just as they would work in the ggplot2 command.
Related
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.
I have a common legend for two ggplot2 graphs which are aligned with grid.arrange() (see code below). However, the legend does not adjust according to graph size, when I export graphs as one pdf.
For a comparison, here is the output of the individual plot:
And after using grid.arrange with the following code:
pdf("Fig1.pdf", onefile=TRUE, paper="a4",width=3.22, height=5)
grid.arrange(Fig1A,Fig1B)
dev.off()
I get this:
The commands for the legend of plot A are:
gglpot2
+theme(legend.key.size=unit(0.5,'lines'))
+theme(legend.key.height=unit(0.25,"cm"))
+theme(legend.key.height=unit(1,"line"))
+theme(legend.text=element_text(size=10))
+theme(legend.position=c(0.85,0.8))
+theme(legend.direction = "vertical")
+guides(fill=guide_legend(title=NULL))
The commands for the legend of plot B are:
+theme(legend.position="")
I tried to solve the issue, according to:
Keep or set the ratio between text labels and size of plot in grid.arrange
which didn’t help, as it is quite similar but not exactly my problem.
https://github.com/baptiste/gridextra/wiki/arranging-ggplot
Here I followed the suggestion:
draw your plots
plot1 <- ggplot(...) # this specifies your first plot
plot2 <- ggplot(...) # this specifies your second plot
plot3 <- ggplot(...) # this specifies your third plot
merge all three plots within one grid (and visualize this)
grid.arrange(plot1, plot2, plot3, nrow=3) #arranges plots within grid
save
g <- arrangeGrob(plot1, plot2, plot3, nrow=3) #generates g
ggsave(file="whatever.pdf", g) #saves g
but I ended up with the same result and worse, as I didn’t have the margins I’d like to have.
https://www.r-bloggers.com/15-questions-all-r-users-have-about-plots/
Printing multiple ggplots into a single pdf, multiple plots per page
didn’t help either, as my problem is not placing the plots on one page, but the ratio of legend size to plot.
Does anyone have a solution?
in the meanwhile I found someone outside this community who was able to help me. The solution is quite simple:
Change the code to
theme(legend.key.size=unit(0.5,'lines'),
legend.key.height=unit(0.32,"cm"),
legend.text=element_text(size=10),
legend.position=c(0.85,0.8),
legend.direction = "vertical")
so basically I removed
theme(legend.key.height=unit(1,"line"))
and
guides(fill=guide_legend(title=NULL))
changed
theme(legend.key.height=unit(0.25,"cm"))
to
theme(legend.key.height=unit(0.32,"cm"))
and that did the job.
I hope this may be usueful for someone else, facing a similar problem.
Best regards!
Attempting to create pie chart with ggplot2 but cannot seem to get it using other references online. The chart I create is missing most of its fill.
ggplot(sae,aes(x=1,fill=factor(State), width=1))+
geom_bar()+
ggtitle("House by State")+
coord_polar(theta='y')
This code gives:
How do I fill the center?
Any other improvements appreciated.
With sample data
sae <- data.frame(State=sample(LETTERS[1:6],60,T))
ggplot(sae,aes(x=factor(1),fill=factor(State)))+
geom_bar(width=1)+
ggtitle("House by State")+
coord_polar(theta="y")
EDIT: Other options (because piecharts are bad)
#following Jaaps example: some better way to visualize this
#grouped barchart
p1 <- ggplot(sae, aes(x=State, fill=State)) +
geom_bar() + labs(title="grouped barchart")
#stacked barchart; especially practical if you want to compare groups
sae$group <- rbinom(60,1,0.5)
p2 <- ggplot(sae, aes(x=factor(group),fill=State))+
geom_bar(width=0.5) + labs(title="grouped stacked barchart")
do.call(grid.arrange,list(grobs=list(p1,p2),ncol=2))
As #Heroka already mentioned in the comments, pie-charts are a bad way of visualizing information. They are bad that it is even mentioned in the help-files of R.
From ?pie:
Pie charts are a very bad way of displaying information. The eye is
good at judging linear measures and bad at judging relative areas. A
bar chart or dot chart is a preferable way of displaying this type of
data.
Cleveland (1985), page 264: “Data that can be shown by pie charts
always can be shown by a dot chart. This means that judgements of
position along a common scale can be made instead of the less accurate
angle judgements.” This statement is based on the empirical
investigations of Cleveland and McGill as well as investigations by
perceptual psychologists.
Some further reading on the pie-chart debate.
With the example data of #Heroka:
ggplot(sae,aes(x = factor(1), fill = factor(State)))+
geom_bar(width = 1, position = "dodge")+
ggtitle("House by State")
you get:
A clear demonstration that it's better to see the differences between the categories when you use a barchart instead of a piechart.
When you want to show information about proportions, there is another choice, the waffle package which gets back more to what you probably intend to show with a pie chart (i.e., proportions). In most instances, the bar plots above would likely be best, but for the sake of showing another way of plotting...
Using the sae data from above:
library(waffle) # install the package if you don't have it
w <- table(sae)
w.waf <- waffle(table(sae))
w.waf + ggtitle("Contextless Waffle Graph") + theme(plot.title=element_text(face="bold", size=24))
which yields this:
I'm trying to plot an histogram for one variable with ggplot2. Unfortunately, the default binwidth of ggplot2 leaves something to be desired:
I've tried to play with binwidth, but I am unable to get rid of that ugly "empty" bin:
Amusingly (to me), the default hist() function of R seems to produce a much better "segmentation" of the bins:
Since I'm doing all my other graphs with ggplot2, I'd like to use it for this one as well - for consistency. How can I produce the same bin "segmentation" of the hist() function with ggplot2?
I tried to input hist at the terminal, but I only got
function (x, ...)
UseMethod("hist")
<bytecode: 0x2f44940>
<environment: namespace:graphics>
which bears no information for my problem.
I am producing my histograms in ggplot2 with the following code:
ggplot(mydata, aes(x=myvariable)) + geom_histogram(color="darkgray",fill="white", binwidth=61378) + scale_x_continuous("My variable") + scale_y_continuous("Subjects",breaks=c(0,2.5,5,7.5,10,12.5),limits=c(0,12.5)) + theme(axis.text=element_text(size=14),axis.title=element_text(size=16,face="bold"))
One thing I should add is that looking at the histogram produced byhist(), it would seem that the bins have a width of 50000 (e.g. from 1400000 to 1600000 there are exactly two bins); setting binwidth to 50000 in ggplot2 does not produce the same graph. The graph produced by ggplot2 has the same gap.
Without sample data, it's always difficult to get reproducible results, so i've created a sample dataset
set.seed(16)
mydata <- data.frame(myvariable=rnorm(500, 1500000, 10000))
#base histogram
hist(mydata$myvariable)
As you've learned, hist() is a generic function. If you want to see the different implementations you can type methods(hist). Most of the time you'll be running hist.default. So if be borrow the break finding logic from that funciton, we come up with
brx <- pretty(range(mydata$myvariable),
n = nclass.Sturges(mydata$myvariable),min.n = 1)
which is how hist() by default calculates the breaks. We can then use these breaks with the ggplot command
ggplot(mydata, aes(x=myvariable)) +
geom_histogram(color="darkgray",fill="white", breaks=brx) +
scale_x_continuous("My variable") +
theme(axis.text=element_text(size=14),axis.title=element_text(size=16,face="bold"))
and the plot below shows the two results side-by-side and as you can see they are quite similar.
Also, that empty bim was probably caused by your y-axis limits. If a shape goes outside the limits of the range you specify in scale_y_continuous, it will simply get dropped from the plot. It looks like that bin wanted to be 14 tall, but you clipped y at 12.5.
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"))