ggplot2: remove geom_tile wired top and bottom block - r

I tried to plot a matrix using geom_tile. However, I noticed there are two strange blocks appear at the top and bottom of my plot. My initial guess was these are ticks element. I've tried to specify the theme parameters as far as I know but no luck.
Basically, I want to remove the two wired blocks that I marked in red arrow. The left plot is something that I desired except the white block. The right plot is I tuned the plot.background in theme to show you there are something I don't know occupies the area.
Image here
I also attached the minimal code that could reproduce the left plot:
test2 <- matrix(runif(100*100),nrow = 100)
testdf <- test2 %>% reshape2::melt()
testdf$Var2 <- factor(testdf$Var2,levels=(seq(max(testdf$Var2),1))) # you could ignore this line
testdf %>% ggplot() + geom_tile(aes(x=Var2,y=Var1,fill=log2(value+1))) +
scale_fill_gradientn(colors = c("#ffffff","#f9c979","#ec8121","#b80217","#2f0006")) +
theme(axis.title = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
legend.title = element_blank(),
panel.background = element_blank(),
panel.border = element_rect(colour = "black", fill=NA, size=1),
plot.background = element_blank()) + coord_equal()

These blocks are the result of ggplot2's default expansion of the scale. To get rid of these block set the expansion to zero via scale_y_continuous:
library(ggplot2)
library(reshape2)
test2 <- matrix(runif(100*100),nrow = 100)
testdf <- reshape2::melt(test2)
testdf$Var2 <- factor(testdf$Var2,levels=(seq(max(testdf$Var2),1))) # you could ignore this line
ggplot(testdf) +
geom_tile(aes(x=Var2,y=Var1,fill=log2(value+1))) +
scale_y_continuous(expand = c(0,0)) +
scale_fill_gradientn(colors = c("#ffffff","#f9c979","#ec8121","#b80217","#2f0006")) +
theme(axis.title = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
legend.title = element_blank(),
panel.background = element_blank(),
panel.border = element_rect(colour = "black", fill=NA, size=1),
plot.background = element_blank()) + coord_equal()

Related

Included rounded medians in a box plot

So I know how to include the medians but I can’t seem to figure out how to round them.
This is what I have so far (if I mess up with how I include the code sorry this is my first time posting)
medians<-aggregate(FGPChange~convert,df,median)
df %>%
ggplot(aes(x=convert, y=FGPChange, fill=convert)) +
geom_boxplot(fill='dark red') +
theme_bw() +
theme(panel.border = element_blank(),
panel.grid.major = element_blank(),panel.grid.minor
= element_blank(), axis.line = element_line(colour =
"black"))+
stat_summary(fun=median, geom="point",shape=18, size=3,
color="red",fill="red")+
geom_text(data=medians,aes(label=FGPChange,y=FGPChange+6.00))+

How to change the plot.background in Donut ggplot graph?

How to change the plot.background in a 'geom_rect()' + 'coord.polar()' in a Donut ggplot graph?
I dont know what I´m missing, but I´w working in html black background style and needing to set panel as well plot background to black, but the graph sides of my ggplot are white and I need to know which attribute or command I need to use to turn sides to black too.
Below my code:
my_df %>%
ggplot(aes(ymax=max, ymin=min, xmax=4, xmin=3,fill=ResultCode)) +
geom_rect() +
geom_label( x=3.5, aes(y=labelPosition, label=label), size=4, color="white") +
coord_polar(theta="y") +
xlim(c(2, 4)) +
theme_void() +
theme(legend.position="none",
plot.background=element_rect(fill = "black"),
panel.background = element_rect(fill = "black"),
panel.border = element_blank(),
legend.key = element_blank(),
axis.ticks = element_blank(),
axis.text.y = element_blank(),
panel.grid = element_blank())
Below the resulted graph (see the "white" sides at right and left I need to fill with black)
The problem here is that ggplot by default calls grid::grid.newpage before drawing. This creates a blank (white) screen. It will then set up a square viewport to fit your plotting window because you are using coord_polar. Once it has done this, it considers the square area to be "the" plotting window. In a sense then, ggplot has no knowledge or control over these white areas. No theme element can touch it.
The solution is to explicitly call grid.newpage yourself, draw a black background manually, and then explicitly print your ggplot using the parameter newpage = FALSE. You could alternatively set the grid gpar parameters so that the background is black by default, but this is likely to have undesired side effects later on.
Here's a reprex with some made-up data:
my_df <- data.frame(max = c(160, 320), min = c(0, 161),
ResultCode = c("A","B"),
labelPosition = c(80, 240), label = c("A", "B"))
p <- my_df %>%
ggplot(aes(ymax=max, ymin=min, xmax=4, xmin=3,fill=ResultCode)) +
geom_rect() +
geom_label( x=3.5, aes(y=labelPosition, label=label), size=4, color="white") +
coord_polar(theta="y") +
xlim(c(2, 4)) +
theme(legend.position="none",
plot.background = element_rect(fill = "black", color = "black"),
panel.background = element_rect(fill = "black", color = "black"),
plot.margin = margin(0,0,0,0),
panel.border = element_blank(),
legend.key = element_blank(),
axis.ticks = element_blank(),
axis.text.y = element_blank(),
panel.grid = element_blank())
grid::grid.newpage()
grid::grid.draw(grid::rectGrob(gp = grid::gpar(fill = "black")))
print(p, newpage = FALSE)

ggplot legend labels and colors

I am struggling with ggplot to produce the legend of this figure. For now, I am only doing for one map, when it works I'l produce the four maps in the same plot.
I would like a legend like this: bottom, title in the center and above the scale, labels and colors, and omit the NA values.
Here is my code:
Reading the shapefile and installing a new variable
map_ev#data$id = rownames(map_ev#data)
map_ev.points = fortify(map_ev, region="id")
map_ev.df = join(map_ev.points, map_ev#data, by="id")
map_ev.df$median_norm = map_ev.df$median / map_ev.df$VOM
Vector with theme opts for ggplot
theme_opts <- list(theme(panel.grid.minor = element_blank(),
panel.grid.major = element_blank(),
panel.background = element_blank(),
panel.border = element_blank(),
axis.line = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.ticks = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
plot.title = element_text(size=12, hjust=0.5),
legend.position = "bottom",
legend.title=element_blank()))
Installing the variable breaks
map_ev.df$median_norm <- cut(map_ev.df$median_norm, breaks=c(-200, -100, -50, -20, -5, 0, 5, 20, 50, 100, +200))
Checking the breaks
levels(map_ev.df$median_norm)
Colors to be used
color_map <- palette(c("#5b2e07", "#904d07", "#b98436", "#dfc27e", "#f6e8c3",
"#c9e9e4", "#84cdc4", "#3c958f", "#01675a", "#073a31"))
ggplot code
ggplot(map_ev.df) +
aes(long,lat,group=group,fill=median_norm, color=median_norm) +
geom_polygon() + geom_path(color="black") +
labs(title="Equivalent variation") + coord_equal() +
theme_opts
For now I am getting this figure:
Thanks all, I appreciate your help!
I just noticed you wanted manual colours for the fill. You can use:
myscale <- c("(-1,10]"="#BBDF27", "(10,20]"="#43BF71", "(20,30]"="#21908C", "(30,50]"="#35608D", "(50,101]"="#482576", "(101,300]"="#ffeeed")
combined with:
scale_fill_manual(values=myscale,na.value="#e0e0e0",name="",labels=c("<10","10 - 20","20 - 30","30 - 50", ">50","Estimate", "NA"))
where scale_fill manual replaces scale_fill_brewer in the other answer.
Just replace the colour and label values with your own. The values that need to go into myscale are shown when you plot your map without any labels. Good luck!
The reason you don't have a title, is because you never specified one, and if you did, you're deleting it again by writing legend.title=element_blank() in theme. Instead I rewrote it to specify the title should be centered. Using guides(colour = guide_legend(title.position = "top"),fill = guide_legend(title.position = "top",nrow=1,byrow=TRUE)) I set the position to "top" and made sure it will only be one row of legend items. (I left colour= here in case you do need it).
You also seem to want black borders, this means I deleted all colour= since that specifies the colour of the borders.
I've added a scale_fill_brewer, there are more color palettes available. Within this you can specify your legend title and the appearance of your legend labels. These need to be manually adjusted every time you change your input data, by the way.
I don't know how to remove the legend item for NA, sorry.
This is the total code I came up with:
ggplot(map_ev.df) +
aes(long,lat,group=group,fill=median_norm) +
scale_fill_brewer(palette="BrBG",name= "Title of legend",labels=c("-200 - -100","-100 - 50","-5 - 0","0 - 5", "label for NA"))+
geom_polygon() + geom_path(color="black") +
labs(title="Equivalent variation") + coord_equal() +
theme(panel.grid.minor = element_blank(),
panel.grid.major = element_blank(),
panel.background = element_blank(),
panel.border = element_blank(),
axis.line = element_blank(),
axis.text.x = element_blank(),
axis.text.y = element_blank(),
axis.ticks = element_blank(),
axis.title.x = element_blank(),
axis.title.y = element_blank(),
plot.title = element_text(size=12, hjust=0.5),
legend.position = "bottom",
legend.direction = "horizontal",
legend.title = element_text(hjust=0.5))+
guides(colour = guide_legend(title.position = "top"),fill = guide_legend(title.position = "top",nrow=1,byrow=TRUE))
Using some data of my own for the fill:
map

Panel border won't fall on x-axis using ggplot2

I am trying to add a panel border to my plot - but the border keeps falling somewhere below the x-axis. Does anyone have any suggestions to have the bottom line of the panel border fall directly on the x-axis.
f<- ggplot(nadph, aes(x = reorder(DGRP.Line, MEN), y = MEN)) +
geom_bar(stat = "identity") +
xlab("DGRP Line") + ylab ("MEN activity (standardized)") +
theme(axis.text.x=element_blank(),
panel.background = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
axis.ticks.x = element_blank(),
panel.border = element_rect(color = "black", fill= NA, size=1))

geom_errorbar and geom_facet

The following code does not display properly the error bars:
rf.imp<- read.csv("importances_byaggregations.csv",head=TRUE,sep=",") #Changes when handling the data
rf.imp$flux <- as.character(rf.imp$flux)
rf.imp$flux<-factor(rf.imp$flux,levels=unique(rf.imp$flux))
rf.imp$aggregation <- as.character(rf.imp$aggregation)
rf.imp$aggregation<-factor(rf.imp$aggregation,levels=unique(rf.imp$aggregation))
cbbPalette <- c("#F0E442", "#CC79A7","#E69F00","#56B4E9", "#009E73") # Mimicking Python colors
rf.imp$rel.influence<-rf.imp$rel.influence*100
rf.imp$SD<-rf.imp$SD*100
limits <- aes(ymax = rf.imp$rel.influence + rf.imp$SD, ymin=rf.imp$rel.influence - rf.imp$SD)
ggplot(rf.imp, aes(variable,rel.influence,fill=variable)) +
geom_bar(stat="identity",position="dodge") + scale_fill_manual(values=cbbPalette)+
theme_bw(base_size = 32, base_family = "Helvetica")+
xlab("")+
ylab("Variable importance (%)")+
facet_grid(aggregation~flux)+
geom_errorbar(limits, width=0.5)+
scale_y_continuous(limits=c(-10,90))+
theme(legend.position="none",
strip.text.x = element_blank(),
strip.text.y = element_blank(),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
strip.background = element_blank(),
panel.border = element_rect(colour = "black"),
panel.border = element_rect(colour = "black", fill=NA, size=1))
I would like to obtaine the following figure, but with the geom_facets swaped.
However, I get something like this:
Am I doing something wrong?
Thanks!
Your minimal example is a little too long for me to dig into, but I strongly suspect that your problem comes from using absolute (rf.imp$...) references in your error bar limits. If you use
geom_errorbar(aes(ymax=rel.influence+SD,
ymin=rel.influence-SD), width=0.5)
I think that will fix the problem.

Resources