Moving facet labels that have two lines near the plotting area - r

I’m working with faceted plots and I’m having an issue trying to move facet labels that have two lines near the plotting area.
Consider the minimal example:
require(ggplot2)
labs <- as_labeller(c(`0` = "LABEL 1",
`1` = "LABEL 2 HAS TWO LINES\nBECAUSE IT'S TOO LONG"))
p <- ggplot(mtcars, aes(disp, drat)) +
geom_point() +
theme_bw() +
geom_hline(yintercept=2, linetype="solid") +
geom_vline(xintercept=50, linetype="solid") +
scale_x_continuous(limits=c(50,500), expand =c(0,0)) +
scale_y_continuous(limits = c(2, 5), expand = c(0,0)) +
theme(panel.border = element_blank(),
strip.background = element_blank(),
strip.text = element_text(size=9),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank()) +
facet_wrap(~am, labeller = labs)
p
Now adding vjust=-0.62 to move the facet labels near the plotting area we have the following:
p + theme(strip.text = element_text(size=9, vjust=-0.62))
As you can see only LABEL 1, the single line label, is moved close to the plotting area - and that’s the problem.
I wished that both labels could have moved. Does anyone have any suggestion?
*Observation: I’m working with a considerable amount of faceted plots so making and customizing plots one-by-one doesn’t seem to be a good idea.

Hope this may helpful for you
p + theme(strip.text = element_text(size=9, vjust=1))

Related

Can't add legend into my graph on ggplot, Why is this the case?

I want to add a legend it shows black for the 7 day moving average and blue for the bars(daily cases). so it looks something similar to the NHS graph , but the legend does not work when i add it into my code?
ggplot(LimerickNew1, aes(x=TimeStamp, y=DailyCCase,Shape=MA7)) +
geom_bar(stat="identity",fill="steelblue") +
geom_line(aes(y=MA7),size=1.5) +
labs( x="", y="Total cases", title="Total Covid Cases for County Limerick 01-03-20 to 01-
06-`20" )+`
theme_bw()+
theme(legend.background = element_rect(fill = "darkgray"),
legend.key = element_rect(fill = "lightblue", color = NA),
legend.key.size = unit(1.5, "cm"),
legend.key.width = unit(0.5,"cm"),
axis.text.x = element_text(face="bold", color="#008000",size=12, angle=0),
axis.text.y = element_text(face="bold", color="#008000",size=12, angle=0),
axis.title.x = element_text(face="bold", size=12, color="black"),
plot.title = element_text( face = "bold", colour = "black", size = 20,, hjust = 0.5))
Without a reproducible example, it's hard to give a more specific answer for your question, but here's a method that expands upon the comment from #teunbrand and should guide you toward showing a legend.
TL;DR - The reason you're not seeing a legend is because you do not have any layers or geoms drawn that have one of the aesthetics mapped to aes(). All aesthetics like color, size, and fill are specified for each geom outside of an aes() function, which means there's no reason for ggplot2 to draw a legend. To get a legend to be drawn, you need to specify the aesthetic inside aes().
Example
Here's an illustrative example that is similar to OP's question.
library(ggplot2)
set.seed(8675309)
df <- data.frame(
x = 1:100,
y = rnorm(100, 10))
df$z <- log(cumsum(df$y))
ggplot(df, aes(x=x)) +
geom_col(aes(y=y), fill='blue', alpha=0.3) +
geom_line(aes(y=z), size=2) +
ylim(0,25) + theme_bw()
Showing a Legend
To get a legend to show, you have to specify one or more aesthetics inside aes(). The fun fact here is that you don't have to specify a column in the dataset when doing this. If you specify a single value, it will apply to the whole dataset, and basically just show a legend key for the entire set of observations. This is what we want.
ggplot(df, aes(x=x)) +
geom_col(aes(y=y, fill="the columns"), alpha=0.3) +
geom_line(aes(y=z, size="the line"), color="black") +
ylim(0,25) + theme_bw()
Formatting
The names come from the values specified in aes(), and the color change is due to default mapping of color values. To get things to look "right", you want to use some theme() elements to:
keep only one name
squish legends together
position on the chart, rather than on the side
The end result is here:
ggplot(df, aes(x=x)) +
geom_col(aes(y=y, fill="the columns"), alpha=0.3) +
geom_line(aes(y=z, size="the line"), color="black") +
ylim(0,25) +
scale_fill_manual(values="blue") + # recolor the columns
guides(
fill=guide_legend(title="My Legend", order=1),
size=guide_legend(title=NULL, order=2)
) +
theme_bw() +
# legend placement and spacing
theme(
legend.title = element_text(margin=margin(b=10)),
legend.spacing.y = unit(-3,'pt'),
legend.position = c(0.8, 0.8)
)

margin text when combining multiple plots into one

I have a series of plots that I want to combine into one, and I cannot use facet_wrap. So each of my plots is a separate object. I want them all the same size, and I can combine them this way.
p = ggplot(mtcars, aes(x=wt, y=mpg)) + geom_point() + xlab("") + ylab("")
g=ggpubr::ggarrange(p, p, p,
p, p, p,
p, p, p,
ncol = 3, nrow = 3)
I want to add some text labels that would apply to the columns and rows, as shown here.
I have tried adding titles to the individual plots (for example, those on the top row), but that reduces the size of the (grayed) plot compared to the others so that the plot dimensions are no longer all the same size.
Any clues would be greatly appreciated.
You can add secondary axes, clear the title for the primary ones and delete the tick marks for secondary ones but keep the titles (look into the theme function I added to your ggplot object). Then tile of those secondary axes can be used to write your desired text. Look below for an example.
library(ggplot2)
library(ggpubr)
p <- ggplot(mtcars, aes(x=wt, y=mpg)) +
geom_point() +
xlab("") + ylab("") +
scale_y_continuous(position = 'right', sec.axis = dup_axis()) +
scale_x_continuous(position = "top", sec.axis = dup_axis()) +
theme(plot.title = element_text(hjust=0.5),
axis.text.x.top = element_blank(),
axis.ticks.x.top = element_blank(),
axis.text.y.right = element_blank(),
axis.ticks.y.right = element_blank(),
axis.title.x.bottom = element_blank(),
axis.title.y.left = element_blank())
ggarrange(p + xlab("some text 1"),
p + xlab("some text 2"),
p + xlab("some text 3") + ylab("some text 33"),
p, p, p + ylab("some text44"),
p, p, p + ylab("some text55"),
ncol = 3, nrow = 3)
You can add axis.title.y.right = element_text(angle = 0) into theme to make y-axis title to be horizontal.
In reference to How to keep axis labels in one side and axis title in another using ggplot2

R | ggplot2 | (remove tick marks + remove panel border) but keep axis lines

novice user here so please be kind and gentle! :)
I am dealing with the following dataset and R script:
#Create pvalue ranges
pvalue <- c(".000 - .005",".005 - .010",".010 - .015",".015 - .020",".020 - .025",".025 - .030",".030 - .035",".035 - .040",".040 - .045",".045 - .050")
#Create frequency counts
count <- c(5000,4000,3100,2540,2390,2260,2150,2075,2050,2025)
dat <- data.frame(pvalue = pvalue, count = count)
#Create plot
myPlot <- ggplot(data=dat, aes(x=pvalue, y=count, group=1)) +
geom_line() +
geom_point() +
geom_vline(xintercept=which(dat$pvalue == '.045 - .050'), linetype = "dashed") +
theme_bw() +
theme(axis.text.x = element_text(angle=90),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank()) +
theme(panel.border = element_blank()) +
ggtitle(paste("Insert Plot Title Here")) +
labs(x = "insert x-axis title here", y = "insert y-axis title here") +
theme(plot.title = element_text(lineheight=0.5,family = "TNR")) +
theme(axis.line.x = element_line(color="black"),
axis.line.y = element_line(color="black")) +
scale_y_discrete(breaks=NULL)
myPlot
The above dataset and R script produce the following plot:
Note that I do not have enough "points" to embed an image so a link to the image has been created by Stack Overflow
An inspection of the image reveals that the left panel border (or the vertical axis) is missing. I want the left panel border to be included in the plot. However, I want to exclude the tick marks on the left panel border (or the vertical axis). Taken together, my desired plot would
include a vertical line for the y-axis,
include a horizontal line for the x-axis,
remove tick marks along the y-axis (vertical axis)
remove the top panel border
remove the right panel border
The above R script takes care of #2-5 in this list. However, I have tried and tried and am unable to figure out how to take care of #1 in this list -- despite including the following in my R script:
theme(axis.line.x = element_line(color="black"),
axis.line.y = element_line(color="black")) +
Can somebody help me to produce the desired image? Very much appreciated :)
The scale_y_discrete(breaks = NULL) breaks the y axis, as it interpret as show nothing.
Removing that line we have the y axis and we can then remove ticks and text:
library(ggplot2)
ggplot(data=dat, aes(x=pvalue, y=count, group=1)) +
geom_line() +
geom_point() +
geom_vline(xintercept=which(dat$pvalue == '.045 - .050'), linetype = "dashed") +
ggtitle(paste("Insert Plot Title Here")) +
labs(x = "insert x-axis title here", y = "insert y-axis title here") +
theme_bw() +
theme(plot.title = element_text(lineheight=0.5,family = "TNR"),
axis.line = element_line(),
axis.ticks.y = element_blank(), ## <- this line
axis.text.y = element_blank(), ## <- and this line
axis.text.x = element_text(angle=90),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(),
panel.border = element_blank())

ggplot2: Add legend and associated legend title to barplot

I have the following barplot which was produced from the data-set 'temp' (the data is situated at the bottom of this stack overflow page and can also be found by following this link above).
PROBLEM
The objective is to add a legend to the right hand side of the barplot (above) titled as Canopy Type with labels denoting Under Canopy and Open Canopy.
I tried using scale_colour_manual as given in another stackoverflow answer but I can't get a legend to show up.
If anyone can help, then many thanks in advance
The code to generate the barplot was:
Assuming you want to plot means of Canopy_Index for each Under_Open, Topography cell, you can form means first:
df.means <- aggregate(Canopy_Index ~ Under_Open + Topography, df.melt, mean)
Then, plot df.means using the code from your question:
ggplot(df.means, aes(x = Topography, y = Canopy_Index,
fill = factor(Under_Open), group = Under_Open)) +
geom_bar(stat = "identity", position = "dodge") +
scale_fill_discrete(name = "Topographical Feature",
breaks = c("Under_tree", "Open_Canopy"),
labels = c("Under Canopy", "Open Canopy")) +
xlab("Topographical Feature") + ylab("Canopy Index") +
scale_colour_manual("Canopy Type", values = c("red", "blue")) +
theme(axis.text.x = element_text(angle = 45, hjust = 1),
text = element_text(size=14)) +
theme(panel.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank()) +
theme(axis.line.x = element_line(color="black", size = 0.8),
axis.line.y = element_line(color="black", size = 0.8))
Many thanks to 'Thales' for providing the code to resolve this problem
Code to produce the barplot with associated legend:
ggplot(df.means, aes(x=Topography, y=Canopy_Index,fill=Under_Open)) +
geom_bar(stat="identity", position="dodge") +
scale_fill_discrete(name="Canopy Type",
breaks=c("Under_tree", "Open_Canopy"),
labels=c("Under Canopy", "Open Canopy")) +
xlab("Topographical Feature") + ylab("Canopy Index")
Barplot

Controlling ticks and odd text in a pie chart generated from a factor variable in ggplot2

I'm generating a simple pie chart with use of the code below:
data(mtcars)
mtcars$fac_var <- as.factor(mtcars$cyl)
require(ggplot2); require(ggthemes)
# Chart
pie_test <- ggplot(mtcars, aes(x = factor(1), fill = fac_var)) +
geom_bar(width = 1) +
coord_polar(theta = "y") +
ggtitle("Title") +
theme_pander() +
scale_fill_tableau(name = "Something") +
theme(axis.title = element_blank())
The code produces the following chart:
I'm interested in introducing two minor modifications to the chart above:
I would like to remove the figure 1 visible on the left (highlighted in red in the picture below).
I would like to make the lines leading to to the figures more strongly pronounced (highlighted in black in the picture below).
Desired changes:
1.) To get rid of the "1-"
edit your theme to:
theme(axis.title = element_blank(),
axis.ticks.y = element_blank(),
axis.text.y = element_blank())
2.) To change the lines edit your theme to:
theme(axis.title = element_blank(),
axis.ticks.y = element_blank(),
axis.text.y=element_blank(),
panel.grid.major.y = element_line(size = 1, color="black", linetype = "solid"))
Not a perfect solution but an improvement. Pie charts are not the best for conveying data. You may want to consider a bar chart. If you want more help with ggplot2 pie charts check out this post.

Resources