How can I change the title of a ggplot2 legend? - r

I was looking here but I can't figure it out.
How can I change the word "type" to something else?

Add
+ labs(colour = "legend title")
to your ggplot call.
Great resource site is also google group for ggplot2.
edit: this assumes that colour is the aesthetic in the legend, e.g. qplot(x,y,colour=z). If another aesthetic is being shown in the legend, use that as the argument instead, e.g. + labs(fill = "legend title") for a raster/image plot.
More generally, if you specify an explicit scale such as scale_colour_continuous, you can set the scale_name argument (warning: the details of the arguments to scales may have changed in recent releases of ggplot2; this description is of version 0.9.2.1).

Add either:
+ scale_fill_discrete(name="Title", labels=c("1","2","3"))
or
+ scale_colour_discrete(name="Title", labels=c("1","2","3"))
depending on the geom.
I recommend you look into the ggplot2 cheatsheet. https://www.rstudio.com/wp-content/uploads/2015/03/ggplot2-cheatsheet.pdf

None of the others worked for me for some reason. In case they failed for you as well, adding this worked for me:
+ guides(fill=guide_legend(title='MY NEW TITLE'))

Just a word to the wise ... all of these options above can be overridden if you do something dumb like I just did. Earlier in my project, I had simply turned off a legend I didn't like using the "themes" parameter within ggplot:
theme(legend.title = element_blank())
If you do this, no matter what beautiful commands you put in to change the title -- and I tried all of those above -- they won't be overridden by your command to turn the legend off! You have been warned! ;{)

Related

Why are R colours not consistent with the eyedropper tool in Powerpoint?

Take the bar graph below as an example:
ggplot(iris, aes(x = Species, y = Sepal.Length,)) + geom_bar(stat = "summary", fill = "#2acaea")
I am trying to use the colour #2acaea. But when I use the eyedropper tool in Powerpoint on the resulting image, it says the colour is #39D0EE.
Which one is right, and why the difference?
Edit: Looks like exporting the image with png() fixes the issue. This problem only applies to the plots as they appear in the R window. Any idea why?
Well, when I do it and upload the image to an online eyedropper - I get #2acaea as expected.
https://imagecolorpicker.com/
SO - I suspect PPT is not respecting the colour palette properly (shocking for an MS product obviously!)
I'm exporting as a PNG from RStudio. The other possibility would be Your export method breaks it... how did you export?

ggplot axes are garbled, look like Unicode boxes

Running Ubuntu 16.04; R 3.6.2; ggplot2 3.3.0
Running R under --nix
If I run this ..
library(ggplot2)
data("midwest", package = "ggplot2")
ggplot(midwest, aes(x=area, y=poptotal))
I get a plot with little boxes for the axes (Unicode?)
I get the same little boxes if I use 'plot'
But If I run 'plot' add a 'family' attribute,
plot (1:10, family="arial")
I get this (nice axes),
This shows that at least some fonts are there!
Back to ggplot ....
The easy solution would be to figure out (I tried) how to set the family in ggplot.
I tried,
ggplot(heightweight, aes(x= ageYear, y=heightIn, font="ariel")) + geom_point()
ggplot(heightweight, aes(x= ageYear, y=heightIn, family="ariel")) + geom_point()
No help .. Little boxes.
Note: It's happy if I put family="Zombie"
Anyone know how to set the family in ggplot?
A better solution?
The hard solution would be for me to figure out which fonts are missing, install them under --nix, and then make sure R (under --nix) can find them.
After much playing I got something to work!
I now get a beautiful title and axes (no more Unicode).
Here's the snippet
ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() +
ggtitle("Fuel Efficiency of 32 Cars") +
xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
theme_bw() +
theme(text=element_text(family="Garamond", size=14))
Apparently the way to set the family in ggplot is using 'theme',
theme(text=element_text(family="Garamond", size=14))
I know it's not a perfect solution but it gets me going (without meds :-) ).
I think it would be worth renaming this issue because it is a Nix specific issue, and was reasonably hard to find. The core issue is caused by a mismatch between the system fontconfig and the one provided by nix.
https://discourse.nixos.org/t/fonts-in-nix-installed-packages-on-a-non-nixos-system/5871/6
I fixed the issue by adding an explicit fontconfig dependency and adding the following to my mkShell command
shellHook = "export FONTCONFIG_FILE=${pkgs.fontconfig.out}/etc/fonts/fonts.conf";
After that opening R from within a nix-shell and generating plots works as expected.

How to force panelView to change linewidth, when there is no option in the package?

I would like to change some graphical features of a panelView plot. In the help menu, I did not find a corresponding option.
I'm not so much into package programming. But I guess they build up on other packages. Perhaps panelView uses ggplot2 or something similar which could be accessed with a workaround? Can I somehow adjust aesthetics?
Here is the MWE from the package. In this case, lines are too thin.
library(panelView)
data(panelView)
panelView(turnout ~ 1 + policy_mail_in + policy_motor, type="outcome",
data = turnout, index = c("abb","year"))
If you look at the source code for panelView, you can see that it hard codes the line width at 0.5. The panelView function does nothing too fancy (like require internals), so you could modify the function so that there is a line width argument. A hacky solution but there is it.
I have done so, but the function is >1300 lines of code, so I'm not doing to repost it here. Rather, you can copy from here.
Now, using the panelView_B function, with the new argument, line.width, we can modify the lines:
library(panelView)
data(panelView)
panelView_B(turnout ~ 1 + policy_mail_in + policy_motor, type="outcome",
data = turnout, index = c("abb","year"), line.width = 1)

degree symbol incorrect in map axis labels

If I create maps using geom_sf, the axis labels have the wrong symbol for degrees. I get degree symbols that are vertically centred in the text, rather than raised like superscipts.
For example,
library(sf)
library(ggplot2)
nc = st_read(system.file("shape/nc.shp", package="sf"))
ggplot() +
geom_sf(data = nc) +
theme(axis.text = element_text(size=16))
When I see examples online, they typically look correct (e.g. image below, copied from here), so I guess it is related to something in my local setup.
I have tried changing font, using library(extrafont) but this problem remains in every font I tried.
Update
I don't think this is a ggplot-specific issue, as I get the same thing with any graphics that uses the degree keyword in plotmath. For example
par(mar=c(0,0,0,0))
plot.new()
text(0.5,0.5, bquote(120*degree*N), cex=5)
I am on Linux (Kubuntu 19.04), R 3.5.2, ggplot2 v. 3.2.1, sf v. 0.7-7.
Not sure what other information might be relevant, but I can update answer with anything else that is requested.
Finally managed to track down the answer:
From ?X11 it says:
Problems with incorrect rendering of symbols (e.g., of quote(pi) and
expression(10^degree)) have been seen on Linux systems which have the
Wine symbol font installed – fontconfig then prefers this and
misinterprets its encoding. Adding the following lines to
‘~/.fonts.conf’ or ‘/etc/fonts/local.conf’ may circumvent this problem
by preferring the URW Type 1 symbol font.
<fontconfig>
<match target="pattern">
<test name="family"><string>Symbol</string></test>
<edit name="family" mode="prepend" binding="same">
<string>Standard Symbols L</string>
</edit>
</match>
</fontconfig>
Adding these lines to /etc/fonts/local.conf solved the problem for me.
I ran into a similar problem and after reading here and some other related issues I found a solution. I'm working with Rstudio, so I guess that if you are doing R without it you you will easily find your work around (hopefully).
My solution was to Tools -> Global Options
and here I changed my backend to Cairo.
This is how it looks the change:
As a workaround I am creating the axis labels manually. Still looking for a better solution and explanation of the undesired behaviour.
xlabs = seq(-84,-76, 2)
ylabs = seq(34, 36.5, 0.5)
ggplot() +
geom_sf(data = nc) +
scale_x_continuous(breaks = xlabs, labels = paste0(xlabs,'°W')) +
scale_y_continuous(breaks = ylabs, labels = paste0(ylabs,'°N')) +
theme(axis.text = element_text(size=16))

Edit style of grid.arrange title. Bold, italic etc. R

I am creating a multi plot in R using grid.arrange, and wanted to change my title so that it is bold (and italic if possible).
As this is a general question, I will not include the code for my plots, but the code I am using to make my multi plot is:
grid.arrange(g1, g3, g4+theme(legend.position="none"),mylegend, top="Test title",
layout_matrix=matrix(c(1,1,2,3,4,4), ncol=2, byrow=TRUE),heights=c(1,1.5,0.3))
Are there any additional arguments which can be passed to the top argument to change the font face?
I've worked it out myself..
You can use the text_grob function to create a text element, which can then be passed to the top function of grid.arrange.
For example,
##title1=textGrob("Test title", gp=gpar(fontface="bold")) ## this does not work anymore
title1=text_grob(main, size = 15, face = "bold") #### this worked for me
grid.arrange(g1, g3, g4+theme(legend.position="none"),mylegend, top=title1, ncol=2, byrow=TRUE),heights=c(1,1.5,0.3))
Just a small update:
Instead of using text
textGrob
use text_grob from ggpubr package

Resources