How do I use ggrepepl to avoid all geoms? - r

I'm trying to use ggrepel to create text labels for charts that I'm working on using R and ggplot2. I'm finding it very useful for repelling away from a single point, but I often run into a problem where it overlaps some other plot objects.
I'm trying to add it to the plot like so:
plot + ggrepel::geom_text_repel(aes(y = Ratio, label = Ratio), direction = "y")
Is there some way that I can tell ggrepel to avoid everything on the ggplot? I've tried searching and coming up with something for this but I'm stuck.
I hope my question is clear enough, thank you.

ggrepel does not allow avoiding all geoms.
In your case, as a workaround, you can use nudge_y = 0.1 in to shift all labels up.
Often, in such cases, you would want more space for the labels. This can be achieved with e.g. + scale_y_continous(expand = scales::expansion(mult = c(0.05, 0.2)))
ggrepel will not label, but repel from, points with a empty ("") label. So in general, as a workaround, you can try to generate data that would cover the other geoms and include that data with empty labels in your geom_text_repel call.

Related

Remembering steps in R [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed last year.
Improve this question
I am a beginner in R and it might appear irrelevant. But can anyone tell me how to remember syntax? like arguments of ggplot or tidyverse or any other package.
There are a few ways to do that. You can start writing the function and press TAB, it will appear in a pop up. You can also check the cheatsheet, here are some
examples: https://www.rstudio.com/resources/cheatsheets/
Or you can check the help topic by writing the function with a ? in it's start, for example: ?ggplot
OP, your question does not relate to coding per se - no problem to solve via issues with code - so it's not really supposed to be on SO. With that being said, it is a viable question and very daunting to approach using ggplot2 to create plots when you really don't have the background for doing so. Consequently, I think you still deserve a good answer, so here are some principles to help out a new user.
Know where to get information
The biggest help to offer is to practice. You will become more familiar with usage, but even "the pros" forget the argument syntax and what stuff does. In this case, the following is helpful:
Use RStudio. The base R terminal is fully capable; however, RStudio brings a ton of conveniences that make programming in R so much easier. Tooltips are an important part of how I create and use functions in R. If you start typing out a function, you'll be presented with a short list of arguments:
What's more, you can start typing an argument and you'll get a description from the help directly within RStudio:
Check the help for functions. This one should be obvious, but I am constantly checking the help for functions on CRAN. This is easily done in RStudio by typing ? before the function. So, if I need to know the arguments and syntax for geom_point(), I'll type ?geom_point into the console and you'll get the documentation directly within RStudio.
Online Resources. A quick search online can give you a lot of information (maybe even this answer). There are a lot of other resources: here too. Including here, here, here, and here.
Become familiar with the Principles of plotting in ggplot2
Knowing where to get information is helpful, but sometimes you feel so lost that you don't even know what information you actually are looking to get. This is the crux of many of the questions here on SO related to ggplot2, which is: "how can I change my axes?", "How do I change colors in the plot?", or "How can I get a legend to show x, y, or z?". Sometimes you can google, but often it's not even clear what you are looking to find.
This is where a fundamental understanding of how to create a plot in ggplot2 becomes useful. I'll go through how I always approach plotting in ggplot2 and hopefully this will help you out a bit.
Step 1 - prepare data
Making your data prepared to plot is exceptionally useful, and sometimes difficult to do. It's a bit beyond what I intend to communicate here, but a mandatory piece of reading would be regarding Tidy Data Principles.
Step 2 - Think about Mapping
Mapping is often overlooked in the process, but in short, this is how the columns of your dataset relate to the plot. It's easy to say "this column will be my x axis" and "this column will be my y axis", but you should also be clear on if the values of other columns will relate to color, fill, size, shape, etc etc... Thinking this way, it will soon be quite obvious why you would want to get Step 1 correct above, because only Tidy data will be able to be used directly in mapping without issue.
Step 3 - The Fundamental ggplot() call
The first step in plotting will be your first call to ggplot(). Here you need to assign data - example via df %>% ggplot(...) or ggplot(data=df, ...). This is also typically where you would setup at least your x and y axes via mapping. You can just stop here (x and y axes), or you can specify the other aesthetics in the mapping here too. Ultimately, this alone plotted "sets up" the plot. If we just plot the result of that, you get the following:
p <- ggplot(mtcars, aes(disp, mpg))
p
Step 4 - Add your geoms
A "geom" (short for "geometry") describes the shapes and "things" on your plot that will be positioned on the x and y axes. You can add any number, but in this example, we'll add points. If all you want to do is plot the observations at the x and y axes, you just need to add geom_point() and that should be enough:
p + geom_point()
Step 5 - Adding Legends
Note we don't have a legend yet. This is because there are no aesthetics mapped other than x and y. ggplot2 creates legends automatically when you specify in the mapping (via aes()) a characteristic way of differentiating the way we draw a geom. In other words, we can describe color= within aes() and that will initiate the creation of a legend. You can do the same with other aesthetics too.
p + geom_point(aes(color=cyl))
This creates a legend type depending on the type of data mapped. So, a colorbar legend is created here because the column mtcars$cyl is numeric. If we use a non-numeric column, you get a discrete legend:
p + geom_point(aes(color=rownames(mtcars)))
There's advanced stuff too... but not covered here.
Step 6 - Adjusting the Scales
All we do when you specify mapping (i.e. aes(color = ...),) is how the data is mapped to that aesthetic. This does not specify the actual color to be used. If you don't specify, the default coloring or sizing is used, but sometimes you want to change that. You can do that via scale_*_() functions... of which there are many depending on your application. For information on color scales, you can see this answer here... but suffice it to say this is quite a complicated part of the plotting stuff that depends greatly on what you want to do. Many of the scale_() functions are structured similarly, so you can probably get an idea of what you can do with that answer and see. Here's an example of how we can adjust the color with one of these functions:
p + geom_point(aes(color=cyl)) +
scale_color_gradient(low="red", high="green")
Step 7 - Adjusting Labels
Here I usually add the plot labels and axis labels. You can conviently use ylab(), or xlab() or ggtitle() to assign axis labels and the title, or just define them all together with labs(y = ..., x = ..., title = ...). You can also use this time to format and arrange things associated with legends and scales (tick marks and whatnot) via guides(...) (for legends) or the scale_x_*() and scale_y_*() functions (for tick marks on axes).
Step 8 - Theme Elements
Finally, you can change the overall look with various ggplot themes. An account of default themes is given here, but you can extend that with the ggtheme package to get more. You might want to just change a few specific elements of size, color, linetype, etc on the plot. You can address these specific elements via theme(). A helpful list of theme elements is given here.
So, putting it all together you have:
# initial call
ggplot(mtcars, aes(disp, mpg)) +
# geoms
geom_point(aes(color=cyl), size=3) +
# define the color scale
scale_color_viridis_c() +
# define labels and ticks and stuff
# axis
scale_x_continuous(breaks = seq(0, 600, by=50)) +
# legend ticks
guides(color=guide_colorbar(ticks.colour = "black", ticks.linewidth = 3)) +
# Labels
labs(x="Disp", y="Miles per gallon (mpg)", color = "# of \ncylinders", title="Ugly Plot 1.0") +
# theme and theme elements
theme_bw() +
theme(
panel.background = element_rect(fill="gray90"),
panel.grid.major = element_line(color="gray20", linetype=2, size=0.2),
panel.grid.minor = element_line(color="gray70", linetype=2, size=0.1),
axis.text = element_text(size=12, face = "bold"),
axis.text.x = element_text(angle=30, hjust=1)
)
It's a lot of steps, but I break it down like that basically every time. When plot code gets large, I break up the chunks much in that manner above to help clear my mind on how to create the plot.

Usage of scale_y_continuous in ggplot2 screws with color fill in area plots

I'm trying to standardize some figures across different types of plots (line and area) and while the usage of scale_y_continuous works perfectly with line plots, when I use the exact same code on an area plot it screws things up a bit.
With the line plot I use the scale_y_continuous argument
scale_y_continuous(breaks= seq(0,1,by=0.2),
labels = c("0.0", 0.2, 0.4, 0.6, 0.8, "1.0"),
limits = c(-0.1,1), expand = c(0,0))
and I get this as the result
So I know that works fine.
Then I try to use the same exact argument with an area plot and it screws the plot up in a way that I don't really have precise language to describe
I'm not entirely certain what's screwing it up here, but if anyone has any input as to how I can remedy this error, I'd greatly appreciate it.
It seems as though simplifying the code to:
scale_y_continuous(breaks= seq(0,1,by=0.2))
resolved the issue.

How to move the legend to outside the plotting area in Plots.jl (GR)?

I have the following plot where part of the data is being obscured by the legend:
using Plots; gr()
using StatPlots
groupedbar(rand(1:100,(10,10)),bar_position=:stack, label="item".*map(string,collect(1:10)))
I can see that using the "legend" attribute, the legend can be moved to various locations within the plotting area, for example:
groupedbar(rand(1:100,(10,10)),bar_position=:stack, label="item".*map(string,collect(1:10)),legend=:bottomright)
Is there any way of moving the plot legend completely outside the plotting area, for example to the right of the plot or below it? For these kinds of stacked bar plots there's really no good place for the legend inside the plot area. The only solution I've been able to come up with so far is to make some "fake" empty rows in the input data matrix to make space with some zeros, but that seems kind of hacky and will require some fiddling to get the right number of extra rows each time the plot is made:
groupedbar(vcat(rand(1:100,(10,10)),zeros(3,10)),bar_position=:stack, label="item".*map(string,collect(1:10)),legend=:bottomright)
I can see that at there was some kind of a solution proposed for pyplot, does anyone know of a similar solution for the GR backend? Another solution I could imagine - is there a way to save the legend itself to a different file so I can then put them back together in Inkscape?
This is now easily enabled with Plots.jl:
Example:
plot(rand(10), legend = :outertopleft)
Using layouts I can create a workaround making a fake plot with legend only.
using Plots
gr()
l = #layout [a{0.001h}; b c{0.13w}]
values = rand(1:100,(10,10))
p1 = groupedbar(values,bar_position=:stack, legend=:none)
p2 = groupedbar(values,bar_position=:stack, label="item".*map(string,collect(1:10)), grid=false, xlims=(20,3), showaxis=false)
p0=plot(title="Title",grid=false, showaxis=false)
plot(p0,p1,p2,layout=l)

R ggplot2 scales cancel each other

I'm having some trouble plotting with ggplot2. When trying to use 2 different scale functions, they won't act at the same time, that is, only one command will actually work, depending on the order. For example, if I do plot + scale_x_discrete(...) and then plot + scale_fill_discrete(...), only the later will work (editing the legend), while the other wont, leaving the x axis unedited. If I switch the order of commands, then the axis is edited, while the legend is neglected.
Could you please explain why this is happening and how I should be doing this?
Did you try
plot + scale_x_discrete(...) + scale_fill_discrete(...)

ggplot2 polar plot axis label location

This is just a extension for a old question
ggplot2 polar plot arrows
You will find the x axis is out of the most_out circle.
In ggplot2, I use "panel.grid.major = theme_line(colour = "black", size = 0.2, linetype=2)" to get the dashed circle, just as below:
So my question is how to make the axis label (180, 135, 90, .....) outside of the circle, because the text are merge with the circular lines.
I try to use "hjust" or "vjust" to adjust the distance between text and axis. But it does not work.
So do you have some ideas about this problem?
Thanks first!!!!
You have not provided code to reproduce the problem so this will be just a guess.
I've used whitespace, \n in particular, to move text "away" in the past. Perhaps a custom formatter might work here. Here is how you can write a custom tick mark label formatter.
If this fails, you can always hide the axis labels and paint them yourself using geom_text by adding another layer.
Hope this helps. #hadley's book on ggplot2 is very good, by the way.
I came across this question while I was trying to fix a similar issue myself. One workaround is pretty much covered in the answer to this post: Remove extra space and ring at the edge of a polar plot
You would have to adjust the limits of the x scale to match your axis labels. You would also have to create a new scale bar corresponding to the radial length of your arrows (the 0-300 scale bar on the left side of your plot), since
axis.text = element_blank
takes the scale bar away as well.

Resources