I have a plot in ggplot that shows me for each category of "rating" the level of price in "bank" and "sistem". This is my code:
##fict
a<-c("rating1","rating2","rating3")
b<-c(1.2,1.2,1.3)
c<-c(1.6,1.4,1.6)
gg<-cbind('rating'=rep(a,2),'price'=c(b,c),'tipo'=rep(c("bank","sistem"),3))
gg<-as.data.frame(gg)
a<-rgb(red=150, green=191, blue=37, maxColorValue = 255)
b<-rgb(red=80, green=113, blue=14, maxColorValue = 255)
ggplot(gg, aes(x=tipo, y=price,width=1)) +
geom_bar(position='stack', stat='identity', fill=c(b,a), color='black') +
facet_wrap( ~ rating)+
theme_bw() + theme(axis.line = element_line(colour = "black"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.border = element_blank(),
panel.background = element_blank(),
strip.background = element_rect(colour = 'white', fill = 'white', size = 3),
axis.title.y=element_text(vjust=0.19),
axis.title.x=element_text(vjust=0.19)
#strip.text.x = element_text(colour = 'red', angle = 45, size = 10, hjust = 0.5, vjust = 0.5, face = 'bold')
) + xlab("My x label") +
ylab("My y label") +
labs(title = 'difference')
This code generates my plot.
I'd like to change 3 things:
I'd like that the labels rating shows in the bottom
I'd like that the "bank" and "sistem" labels disappear and change it with the legend with colors for bank and sistem.
If it's possible also put the legend under the x-axis title in horizontal way
Thank you
Upgrade comment to an answer.
library(ggplot2)
# your data - tweaked the code - there is no need to cbind within data.frame
# and names do not need to be in quotes
gg <- data.frame(rating=rep(c("rating1","rating2","rating3"),2),
price=c(c(1.2,1.2,1.3),c(1.6,1.4,1.6)),
tipo=rep(c("bank","sistem"),3))
a <- rgb(red=150, green=191, blue=37, maxColorValue = 255)
b <- rgb(red=80, green=113, blue=14, maxColorValue = 255)
# Plot
# use position dodge to get the bars side-by-side
# theme_classic removes grid lines and uses theme_bw()
# scale_fill_manual to manually specify the colours - by using fill = tipo in the
# aesthetic call of ggplot a legend will be generated
# scale_y_continuous - using expand starts the axis at exactly zero
ggplot(gg, aes(x=rating, y=price, fill=tipo)) +
geom_bar(position='dodge', stat='identity', color='black') +
theme_classic() +
scale_fill_manual(values = c(b,a)) +
scale_y_continuous(limit=c(0,2), expand=c(0,0)) +
labs(title = 'difference', x = "My x label", y = "My y label") +
theme(
axis.title.y=element_text(vjust=0.19),
axis.title.x=element_text(vjust=0.19) ,
legend.position = "bottom",
legend.title=element_blank())
Related
Here I have theme_light() but in the plot I still have the x/y axis & legend + grid. I want to remove those and only have my light background + plot 'pic'. When I use theme_void -> it removes the legend but then the background is void. Any idea how to solve this so I only have a white background and my plot?
pic <- ggplot(data = art_dat, mapping = aes(x = x, y = y, group = path_id,
color = step_id)
) +
geom_path(
size = .9,
alpha = 1000, #transparency of the lines
show.legend = FALSE
) +
coord_equal() +
theme_light() +
scale_color_scico(palette = "berlin")
EDIT: Updated as you have posted an image. You do not have a legend, so you do not need to remove it. You want to remove the axis lines, ticks, text, title and maybe(?) the panel grid lines:
pic <- ggplot(data = art_dat, mapping = aes(x = x, y = y, group = path_id,
color = step_id)
) +
geom_path(
size = .9,
alpha = 1000, #transparency of the lines
show.legend = FALSE
) +
coord_equal() +
theme_light() +
scale_color_scico(palette = "berlin") +
theme(
axis.line = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank(),
axis.title = element_blank(),
panel.grid.major = element_blank(), # optional - remove gridlines
panel.grid.minor = element_blank() # optional - remove gridlines
)
If you add some adjustments to theme void, you can get rid of the legend. In addition, you can make the legend white with the plot.background argument. In the example below I made it red to show that there are no margins left and such. There is a row of white pixels, but I don't know what to do against that.
library(ggplot2)
p <- ggplot(mpg, aes(displ, hwy, colour = cyl)) +
geom_point()
p + theme_void() +
theme(
legend.position = "none",
plot.background = element_rect(fill = "red", colour = NA)
)
Created on 2022-01-18 by the reprex package (v2.0.1)
I have 3 plots, with two plots stacked on top of each other to appear as one plot. I made a side by side (2 column) plot so it looks like 2 plots next to each other (although again, the one plot is actually two plots stacked). I have two problems:
No matter what I try (vjust, scale, etc) I can't get the bottom of the two side-by-side plots to be even.
I can't get a Y axis label centered on the stacked plot, because you can't make a label that spans two plots. I've tried using "title" for the whole panel, but then I can't change the font size to match the rest of the labels.
I've tried using vjust, adding a title to the entire plot, using plot_grid instead, and everything else I can think of.
city<-c("A", "B", "A", "B", "A", "B")
temp<-c(20, 25, 300, 35, 30, 400)
data1<-data.frame(city, temp)
library(cowplot)
library(gridExtra)
g.top <- ggplot(data1[data1$variable == "city A", ], aes(x = temp))
+
geom_histogram(binwidth=1) +
scale_x_continuous(limits = c(0, 100), position = "top") +
scale_y_reverse(limits = c(400, 0))+
theme_minimal(base_size = 16) + theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line =
element_line(colour = "black"))+
annotate("text", x=20, y=200, cex=6, label= "city A")+ labs(title="a",
y="Count")+theme(axis.title.x=element_blank())
g.bottom <- ggplot(data1[data1$variable == "city B", ], aes(x =
temp)) +
geom_histogram(binwidth=1) +
scale_x_continuous(limits = c(0, 100)) + ylim(0, 400)+
theme_minimal(base_size = 16)+ theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
panel.background = element_blank(), axis.line =
element_line(colour = "black"))+
annotate("text", x=20, y=200, cex=6, label= "city B") + labs(x =
expression("Temp (F)"), y="")
mean<-c(2, 6)
se<-c(0.01, 0.3)
city<-c("A","B")
df<-data.frame(mean, se, city)
gg<- ggplot(df, aes(x=city, y=mean, group=city,
color=city, shape=city)) +
geom_line(size=1, position=position_dodge(0.2))+
geom_jitter(aes(shape=city, size=city), alpha=1,
position=position_dodge(0.2))+
geom_errorbar(aes(ymin=mean-se, ymax=mean+se), width=.4,
position=position_dodge(0.2))+
labs(title= "b", x= expression("City"), y =expression("Temp (F)"))+
theme_bw(base_size = 16) + theme(axis.title.x =
element_text(vjust=200000000), axis.title.y = element_text(vjust=-7),
legend.title=element_blank())+
theme(legend.justification=c(0.1,0.1), legend.position=c(0.6,0.1))+
scale_color_manual(values=c('#104E8BC8','#FF8C00C8'))+
scale_size_manual(values=c(4,4))+
scale_shape_manual(values=c(19, 17))+theme(legend.position="none")+
theme(axis.ticks.length=unit(-0.25, "cm"), axis.ticks.margin=unit(0.5,
"cm"),axis.text.x = element_text(margin=unit(c(0.5,0.5,0.5,0.5),
"cm")),axis.text.y = element_text(margin=unit(c(0.5,0.5,0.5,0.5), "cm")))
grid.arrange(arrangeGrob(g.top, g.bottom), gg, ncol = 2)
You can use the patchwork package to lay out the plots. See the Vignette for details on how the layout system works:
To install package from github:
devtools::install_github("thomasp85/patchwork")
Then,
library(patchwork)
{g.top + g.bottom + plot_layout(ncol=1)} - gg
I need to create a ggplot that is a column plot overlayed with a line plot. The line plot shows mean values, while the column plot shows how the mean values relate to benchmark values. I've managed to create two separate plots in ggplot, but I'm having trouble combining them.
My line plot looks like this:
And is created using this code:
benchMarkLine <- ggplot(UEQScores, aes(x=Scale, y=Score, group=1)) +
geom_line(size = 1.4, colour = "black") +
geom_point(size = 2.4, colour = "black") +
scale_y_continuous(name = "Score", breaks = seq(0, 2.5, 0.25), limits = c(0, 2.5)) +
scale_x_discrete(name = "Scale") +
ggtitle("Mean Scores") +
theme_bw() + # Set black and white theme +
theme(plot.title = element_text(hjust = 0.5, size=10), # Centre plot title
panel.grid.major = element_blank(), # Turn off major gridlines
panel.grid.minor = element_blank(), # Turn off minor gridlines
axis.title.x = element_text(size=10),
axis.text.x = element_text(angle=30, vjust=0.6),
axis.title.y = element_text(size=10))
benchMarkLine
My Column plot looks like this:
And was created with the following code:
benchmarkColPlot <- ggplot(benchmark_long, aes(x=factor(Scale, scaleLevels), y=value, fill=factor(cat, bmLevels))) +
geom_col(position="fill") +
scale_fill_manual(values = bmColours) +
scale_y_continuous(name = "Score", breaks = seq(-1.0, 1.0, 0.25), limits = c(-1, 1)) +
scale_x_discrete(name = "Scale") +
ggtitle("Benchmark Scores") +
theme_bw() + # Set black and white theme +
theme(plot.title = element_text(hjust = 0.5, size=10), # Centre plot title
panel.grid.major = element_blank(), # Turn off major gridlines
panel.grid.minor = element_blank(), # Turn off minor gridlines
axis.title.x = element_text(size=10),
axis.text.x = element_text(angle=30, vjust=0.6),
axis.title.y = element_text(size=10),
legend.title = element_blank())
benchmarkColPlot
How can I combine these two? I tried inserting geom_line(UEQScores, aes(x=Scale, y=Score, group=1)) + above geom_col(position="fill") + in the column plot code, but I just get the following error:
Error: `mapping` must be created by `aes()`
How do I combine these two plots?
OK, I've given up on this - I just created the chart in Excel as it seems to be a bit easier for what I'm doing here.
I need my charts to have a dark gray theme to match a presentation style. I also need them to be fixed height, but the widths may vary depending on the length of the labels on the y-axis. When I try to export or save, there are always white side bars in the .jpg or .png file.
Here's some sample code that I use to create the chart (there are some extra theming controls in here that are superfluous to the simplified example, but the resulting chart is basically what I am generating):
library(ggplot2)
bar.font <- 8
title <- "Example"
l_labs <- c("")
x_labs <- c("A","B","C")
ests <- c(.5,.3,.2)
nerrs <- c(.05, .05, .05)
perrs <- nerrs
barchart.data <- data.frame(l_labs, x_labs, ests, nerrs, perrs)
p <- ggplot(barchart.data, aes(x=x_labs, y=ests*100)) +
geom_bar(stat="identity", color="#808080", position=position_dodge(), width=0.85, fill="#808080") +
geom_text(aes(y=ests*100+perrs*100+1.5, label=sprintf("%1.1f%%", 100*ests)), vjust=0.5, hjust=0, size=bar.font, color="white") +
geom_errorbar(aes(ymin=ests*100-nerrs*100, ymax=ests*100+perrs*100), width=.2, position=position_dodge(.9), color="white", size=0.25) +
labs(title=title, x="", y = "") + theme_classic() +
scale_y_continuous(expand = c(0,0),limits = c(0,115), breaks=c(0, 20, 40, 60, 80, 100)) +
theme(legend.position="none", legend.text = element_text(color = "white")) +
theme(title = element_text(size=18, colour = "white")) +
theme(axis.text = element_text(size=20, color = "white"), axis.line = element_line(color = "white")) +
theme(axis.text.x = element_text(margin=margin(9,0,0,0)),axis.text.y = element_text(margin=margin(0,9,0,0))) +
theme(axis.title = element_text(size=20, color = "white")) +
theme(axis.title.x = element_text(margin = margin(10,0,0,0))) +
theme(axis.ticks = element_line(colour = 'white', size = .5)) +
coord_flip() +
theme(aspect.ratio = 1) +
theme(panel.background = element_rect(fill = "#1e1e1e")) +
theme(legend.justification=c(1,0), legend.position=c(1,0)) +
theme(plot.background = element_rect(fill = "#1e1e1e", color = "#1e1e1e")) +
theme(panel.grid.major.x = element_line(colour = "white",size=0.1, linetype = "dotted"))
ggsave("test.jpg", height=10, units="in")
And here is what the exported .jpg looks like. I cannot specify an exact width because I do not know what it will be for each chart as the widths vary. Thanks for any guidance.
You can set the background color to whatever value you like:
ggsave("test.jpg", height=10, units="in", bg = "#1e1e1e")
This takes care of the white bars.
It may be a bit confusing that the bg option is not mentioned in the ggsave() documentation. That's because it's part of the graphics device, here jpeg(). It is mentioned in the jpeg() documentation.
The reason why there are white bars in the first place is discussed in depth in this post.
I have been trying to shift my legend title across to be centered over the legend contents using the guide function. I've been trying to use the following code:
guides(colour=guide_legend(title.hjust = 20))
I thought of trying to make a reproducable example, but I think the reason it's not working has something to do with the above line not matching the rest of my code specifically. So here is the rest of the code I'm using in my plot:
NH4.cum <- ggplot(data=NH4_by_Date, aes(x=date, y=avg.NH4, group = CO2, colour=CO2)) +
geom_line(aes(linetype=CO2), size=1) + #line options
geom_point(size=3) + #point symbol sizes
#scale_shape_manual(values = c(1, 16)) + #manually choose symbols
theme_bw()+
theme(axis.text.x=element_text(colour="white"), #change x axis labels to white.
axis.title=element_text(size=12),
axis.title.x = element_text(color="white"), #Change x axis label colour to white
panel.border = element_blank(), #remove box boarder
axis.line.x = element_line(color="black", size = 0.5), #add x axis line
axis.line.y = element_line(color="black", size = 0.5), #add y axis line
legend.key = element_blank(), #remove grey box from around legend
legend.position = c(0.9, 0.6))+ #change legend position
geom_vline(xintercept=c(1.4,7.5), linetype="dotted", color="black")+ #put in dotted lines for season boundaries
scale_color_manual(values = c("#FF6600", "green4", "#0099FF"),
name=expression(CO[2]~concentration~(ppm))) + #manually define line colour
scale_linetype_manual(guide="none", values=c("solid", "solid", "solid")) + #manually define line types
scale_shape_manual(values = c(16, 16, 16)) + #manually choose symbols
guides(colour=guide_legend(title.hjust = 20))+
scale_y_continuous(expand = c(0, 0), limits = c(0,2200), breaks=seq(0,2200,200))+ #change x axis to intercept y axis at 0
xlab("Date")+
ylab(expression(Membrane~available~NH[4]^{" +"}~-N~(~mu~g~resin^{-1}~14~day^{-1})))+
theme(panel.grid.major = element_blank(), panel.grid.minor = element_blank())+
geom_errorbar(aes(ymin = avg.NH4 - se.NH4, #set y error bars
ymax = avg.NH4 + se.NH4),
width=0.1)
I have tried doing the following instead with no luck:
guides(fill=guide_legend(title.hjust=20)
I have also adjusted the hjust value from values between -2 to 20 just to see if that made a difference but it didn't.
I'll try to attach a picture of the graph so far so you can see what I'm talking about.
I've looked through all the questions I can on stack overflow and to the best of my knowledge this is not a duplicate as it's specific to a coding error of my own somewhere.
Thank-you in advance!!
The obvious approach e.g.
theme(legend.title = element_text(hjust = .5))
didn't work for me. I wonder if it is related to this open issue in ggplot2. In any case, one manual approach would be to remove the legend title, and position a new one manually:
ggplot(mtcars, aes(x = wt, y = mpg, colour = factor(cyl))) +
geom_point() +
stat_smooth(se = FALSE) +
theme_bw() +
theme(legend.position = c(.85, .6),
legend.title = element_blank(),
legend.background = element_rect(fill = alpha("white", 0)),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank()) +
annotate("text", x = 5, y = 27, size = 3,
label = "CO[2]~concentration~(ppm)", parse = TRUE)
Output: