I am trying to label the ticks on the x-axis using the following line of code:
scale_x_discrete("Results of the urine culture", labels=c(expression("<"~10^4~"CFU/ml"), expression(10^4~"-"~10^5~"CFU/ml"), expression(">"~10^6~"CFU/ml")))
The graph returns with the same value (the first in the expression, i.e. "<10^4 CFU/ml") for all three ticks. I have tried to find an answer using search but did not find the description of this problem. Could you please point out what is wrong with this code?
Thanks in advance.
Edit
DF %>%mutate(count=paste("N=", count, sep="")) %>%
group_by(uc.res) %>%
ggplot(mapping = aes(x = uc.res, y = tts.0)) +
geom_boxplot()+
scale_x_discrete("Results of the urine culture",
labels=c(expression("<"~10^4~"CFU/ml"), expression(10^4~"-"~10^5~"CFU/ml"), expression(">"~10^6~"CFU/ml")))+
facet_grid(~count, switch="y", space = "free_x", scales = "free_x")+
theme(panel.spacing = unit(0, "lines"), strip.background = element_blank(), strip.placement = "outside")
Dear all problem was in the line
facet_grid(~count, switch="y", space = "free_x", scales = "free_x")
But if I remove it, I lose the number of cases in each group, that I would like to avoid.
Update: Well, I have found the solution. I have removed the line with facet_grid and added some modifications to keep these numbers at the top of the graph. First, I tried to duplicate the x-axis using sec_axis to add the numbers of patients in each group on the secondary axis. But doesn't work because the x-axis was discrete and sec_axis works only with continuous axes. Then, I have tried simple geom_text, adding some modifications with coord_cartesian and plot.margin. So, the added modifications are:
+geom_text(aes(label=count, y=Inf), vjust=-0.5, size=5)+
coord_cartesian(clip = "off")+
theme(plot.margin = margin(20,15,15,15, unit = "pt"))
Related
I've created a correlation matrix:
cor_matrix = cor(qual_colleges_all_data_clean[ ,c(4,5,8,9,10,12,13,14,16,20,21,22,23,25)], method='pearson',use='complete.obs')
ggcorrplot(cor_matrix, hc.order = TRUE, method ='circle', type='lower', colors = c("darkblue", "white", "red")) +
labs(title = "Correlation Matrix:", subtitle = "Select Variables") +
theme_minimal() +
theme(
legend.key.width = unit(0.6, "cm"),
legend.key.height = unit(1.3, "cm"),
axis.text.x = element_text(angle = 45) #to put x-axis labels at 45 angles
)
Here's what it looks like:
Initially the x-axis labels were all horizontal and thus were a jumbled mess, so I angled them. But as you can see, they're overlapping the plot. The problem is that I need to preserve theme_minimal() if at all possible. I've tried every theme() adjustment I could find online, but I cannot make anything work. So, I have three questions:
How can adjust the x-axis headings while preserving theme_minimal()?
How can I widen the plot while preserving theme_minimal()? My hope is that will space the circles a bit more suitably.
How can I eliminate the Var2 and Var1 axis labels while preserving theme_minimal()?
I realize these are basic questions, so I really appreciate you taking the time to help me. Thanks in advance!
I was wondering if you can help me out with a (probably silly) problem with my code that is driving me nuts. I'm using R and my problems are with the package sf + ggplot2. Is there anyone out there that can help me?. I found a similar question here, but the solution is not exactly what I need.
I'm trying to plot a numeric variable on a map using the sf package. The variable is numeric and I want the legend to be on a continuous scale. I managed to do that, the problem started when I used the "guides" option to position the title of the legend on top. Here is a reproducible example:
library(sf)
demo(nc, ask = F, echo = F)
ggplot() +
geom_sf(data = nc, aes(fill = BIR74)) +
scale_y_continuous(breaks = 34:36) +
theme(legend.position="bottom",
legend.direction = "horizontal")
This code produces this map:. You can see that the scale of the Bir74 is continuous. If I use guides(fill = guide_legend(title.position = “top”), it will work for placing the title of the legend on top, but the legend label is on a discrete scale now. This is an example
ggplot() +
geom_sf(data = nc, aes(fill = BIR74)) +
scale_y_continuous(breaks = 34:36) +
theme(legend.position="bottom",
legend.direction = "horizontal") +
guides(fill = guide_legend(title.position = "top"))
and this is the map resulting:
What I really want is the legend placed at the bottom with the title on top as in map 2, but with the legend on the scale of map 1.
Any help on how to solve this would be massively appreciated!
Cheers!
I'm having some issues with ggplot2 and y axis tick marks - if someone can provide any input I'd really appreciate it.
I'm trying to create a 'stacked' plot with independent y axis for publication I'm working on. The idea is to have N plots stacked with a common X axis but distinct Y axes for each subplot while making it seem like a single contiguous plot.
I would like inverted tick marks on the x axis (for the bottom most subplot) and all the y axes. Problem is while the tick marks show up on the yaxis breifly in the plot generation they seem to be overwritten at the last stage and become invisible. Its such a minor thing and I could just leave them off but I'd really like to know what is going on for my own sanity...
Below is some sample code that should reproduce the problem and here is an imgur link highlighting the plot style and missing tick marks.
On a tangent, if anyone knows how to customize the axis.line.y.right / axis.line.x.top without using a dummy 'second axis' let me know (it seems a very verbose way of doing something that should be simple).
Thanks for your help
ylim=c(-5,5)
xlim=c(3,12)
ybreaks=c(-2,2)
base <- ggplot() +
theme_bw() +
scale_y_continuous(limits=ylim, breaks=ybreaks) +
scale_x_continuous(limits=xlim) +
labs(x="", y="") +
theme( panel.grid.major=element_line("gray78",0.5,1),
panel.border=element_blank(),
axis.text.x=element_blank(),
axis.text.y=element_text(margin=unit(c(0,3,0,0), "mm")))
bottom <- base + xlab("xlab") +
theme( axis.ticks.length.y=unit(-2,"mm"),
axis.ticks.length.x=unit(-2,"mm"),
axis.line.y=element_line(),
axis.line.x=element_line(),
plot.margin=unit(c(0,5,5,5),"mm"),
axis.text.x=element_text(margin=unit(c(3,0,0,0), "mm")))
middle <- base +
theme( axis.ticks.length.y=unit(-2,"mm"),
axis.ticks.length.x=unit(0,"mm"),
axis.line.y=element_line(),
axis.line.x=element_line(linetype=3),
plot.margin=unit(c(0,5,0,5),"mm"),
axis.title=element_blank())
top <- base +
theme( axis.ticks.length.y=unit(-2,"mm"),
axis.ticks.length.x=unit(0,"mm"),
axis.line.y=element_line(),
axis.line.x=element_line(linetype=3),
plot.margin=unit(c(5,5,0,5),"mm"),
axis.title=element_blank())
ggarrange(top,middle,bottom,ncol=1)
The easiest and more ggplot-y way would be to use facets.
I recommend using labs(x=NULL, y=NULL), because using = '' actually is drawing something.
I am removing the facet strips in the plot, but I generally think your graph may be slightly less confusing when you keep the labels and also keep a bit of distance between those graphs.
In order to add the dashed lines between your facets, you could simply add annotations, e.g., with annotate(geom = 'segment')
library(ggplot2)
ylim=c(-5,5)
xlim=c(3,12)
ybreaks=c(-2,2)
ggplot(data.frame(facet = letters[1:3])) +
theme_bw() +
annotate(geom = 'segment', x = -Inf, xend = Inf, y = -Inf, yend = -Inf, linetype = 3)+
scale_y_continuous(limits=ylim, breaks=ybreaks) +
scale_x_continuous(limits=xlim) +
labs(x=NULL, y=NULL) +
theme( panel.grid.major=element_line("gray78",0.5,1),
panel.border=element_blank(),
axis.text.x=element_blank(),
axis.text.y=element_text(margin=unit(c(0,3,0,0), "mm")),
panel.spacing = unit(0, "lines"),
strip.background = element_blank(),
strip.text = element_blank(),axis.line.y=element_line(),
axis.line.x=element_line(),
axis.ticks.length.y=unit(-2,"mm"),
axis.ticks.length.x=unit(-2,"mm"),
plot.margin=unit(c(b = 5, t = 5, r = 5, l = 5),"mm")) +
facet_wrap(~facet, nrow = 3)
Created on 2020-02-22 by the reprex package (v0.3.0)
Here is my reproducible code:
This is an example of what I want my actual figure to look like.
library(tidyverse)
p <- mtcars %>%
mutate(cyl = factor(cyl)) %>%
ggplot(aes(carb)) +
geom_bar(aes(fill = cyl)) +
scale_fill_manual(values = c("Red","Green","Blue"))
Resulting figure:
Problem:
What I want to change is in the legend. The boxes depicting the color of the bars on the histogram are too big and I want to reduce the size.
Attempted Solutions:
I have tried this code from another stackoverflow question and it does not work:
p <- p + guides(fill = guide_legend(override.aes = list(width = .5)))
In the reference stackoverflow question, another user suggested making a dummy geom_point variable and then using that legend as the legend and removing the fill legend. I would rather not have to do that if possible.
Thank you for the help.
Use legend.key.size (or legend.key.height and legend.key.width). E.g., add
theme(legend.key.size = unit(0.1, "cm"))
to your plot
I'd like to remove the labels for the facets completely to create a sort of sparkline effect, as for the audience the labels are irrelevant, the best I can come up with is:
library(MASS)
library(ggplot2)
qplot(week,y,data=bacteria,group=ID, geom=c('point','line'), xlab='', ylab='') +
facet_wrap(~ID) +
theme(strip.text.x = element_text(size=0))
So can I get rid of the (now blank) strip.background completely to allow more space for the "sparklines"?
Or alternatively is there a better way to get this "sparkline" effect for a large number of binary valued time-series like this?
For ggplot v2.1.0 or higher, use element_blank() to remove unwanted elements:
library(MASS) # To get the data
library(ggplot2)
qplot(
week,
y,
data = bacteria,
group = ID,
geom = c('point', 'line'),
xlab = '',
ylab = ''
) +
facet_wrap(~ ID) +
theme(
strip.background = element_blank(),
strip.text.x = element_blank()
)
In this case, the element you're trying to remove is called strip.
Alternative using ggplot grob layout
In older versions of ggplot (before v2.1.0), the strip text occupies rows in the gtable layout.
element_blank removes the text and the background, but it does not remove the space that the row occupied.
This code removes those rows from the layout:
library(ggplot2)
library(grid)
p <- qplot(
week,
y,
data = bacteria,
group = ID,
geom = c('point', 'line'),
xlab = '',
ylab = ''
) +
facet_wrap(~ ID)
# Get the ggplot grob
gt <- ggplotGrob(p)
# Locate the tops of the plot panels
panels <- grep("panel", gt$layout$name)
top <- unique(gt$layout$t[panels])
# Remove the rows immediately above the plot panel
gt = gt[-(top-1), ]
# Draw it
grid.newpage()
grid.draw(gt)
I'm using ggplot2 version 1 and the commands required have changed.
Instead of
ggplot() ... +
opts(strip.background = theme_blank(), strip.text.x = theme_blank())
you now use
ggplot() ... +
theme(strip.background = element_blank(), strip.text = element_blank())
For more detail see http://docs.ggplot2.org/current/theme.html
Sandy's updated answer seems good but, possibly has been rendered obsolete by updates to ggplot? From what I can tell the following code (a simplified version of Sandy's original answer) reproduces Sean's original graph without any extra space:
library(ggplot2)
library(grid)
qplot(week,y,data=bacteria,group=ID, geom=c('point','line'), xlab='', ylab='') +
facet_wrap(~ID) +
theme(strip.text.x = element_blank())
I am using ggplot 2.0.0.
As near as I can tell, Sandy's answer is correct but I think it's worth mentioning that there seems to be a small difference the width of a plot with no facets and the width of a plot with the facets removed.
It isn't obvious unless you're looking for it but, if you stack plots using the viewport layouts that Wickham recommends in his book, the difference becomes apparent.