GGPlot2 axis ticks and tick labels not following theme specification - r

I am trying to set perfectly black ticks and labels in ggplot2 but they are coming with a very slight grey tint. Here is an example:
library(tidyverse)
mpg %>% ggplot(aes(x = cty, y = cyl)) + geom_point() + theme_classic() +
theme(line = element_line(size = 4,color = "black",lineend = "square"),
text = element_text(color = "black", face = "bold",size = 24))
Plots this:
The color difference in the ticks is subtle but noticeable.

Try this approach with modifications on theme():
library(tidyverse)
mpg %>% ggplot(aes(x = cty, y = cyl)) + geom_point() + theme_classic() +
theme(axis.text = element_text(color = "black", face = "bold",size = 24),
line = element_line(size = 4,color = "black",lineend = "square"),
text = element_text(color = "black", face = "bold",size = 24),
axis.ticks = element_line(size = 4,color = "black",lineend = "square"))
Output:

Related

How to set a conditional size scale based on name in ggplot?

Below is a simple bubble plot for three character traits (Lg_chr, Mid_chr, and Sm_chr) across three locations.
All good, except that because the range of Lg_chr is several orders of magnitude larger than the ranges for the other two traits, it swamps out the area differences between the smaller states, making the differences very difficult to see - for example, the area of the points for for Location_3's Mid_chr (70) and Sm_chr (5), look almost the same.
Is there a way to set a conditional size scale based on name in ggplot2 without having to facit wrap them? Maybe a conditional statement for scale_size_continuous(range = c(<>, <>)) separately for Lg_chr, Mid_chr, and Sm_chr?
test_df = data.frame(lg_chr = c(100000, 150000, 190000),
mid_chr = c(50, 90, 70),
sm_chr = c(15, 10, 5),
names = c("location_1", "location_2", "location_3"))
#reformat for graphing
test_df_long<- test_df %>% pivot_longer(!names,
names_to = c("category"),
values_to = "value")
#plot
ggplot(test_df_long,
aes(x = str_to_title(category),
y = str_to_title(names),
colour = str_to_title(names),
size = value)) +
geom_point() +
geom_text(aes(label = value),
colour = "white",
size = 3) +
scale_x_discrete(position = "top") +
scale_size_continuous(range = c(10, 50)) +
scale_color_manual(values = c("blue", "red",
"orange")) +
labs(x = NULL, y = NULL) +
theme(legend.position = "none",
panel.background = element_blank(),
panel.grid = element_blank(),
axis.ticks = element_blank()) ```
Edit:
You could use ggplot_build to manually modify the point layer [[1]] to specify the sizes of your points like this:
#plot
p <- ggplot(test_df_long,
aes(x = str_to_title(category),
y = str_to_title(names),
colour = str_to_title(names),
size = value)) +
geom_point() +
geom_text(aes(label = value),
colour = "white",
size = 3) +
scale_x_discrete(position = "top") +
scale_color_manual(values = c("blue", "red",
"orange")) +
labs(x = NULL, y = NULL) +
theme(legend.position = "none",
panel.background = element_blank(),
panel.grid = element_blank(),
axis.ticks = element_blank())
q <- ggplot_build(p)
q$data[[1]]$size <- c(7,4,1,8,5,2,9,6,3)*5
q <- ggplot_gtable(q)
plot(q)
Output:
You could use scale_size with a log10 scale to make the difference more visuable like this:
#plot
ggplot(test_df_long,
aes(x = str_to_title(category),
y = str_to_title(names),
colour = str_to_title(names),
size = value)) +
geom_point() +
geom_text(aes(label = value),
colour = "white",
size = 3) +
scale_size(trans="log10", range = c(10, 50)) +
scale_x_discrete(position = "top") +
scale_color_manual(values = c("blue", "red",
"orange")) +
labs(x = NULL, y = NULL) +
theme(legend.position = "none",
panel.background = element_blank(),
panel.grid = element_blank(),
axis.ticks = element_blank())
Output:

plotting geom_text() with free scale facet_wrap

I would like to plot geom_text() in a facet_wrap with scale = free.
I tried to use geom_blank() or, set each height on each graph, but it was not successful.
Would you possibly tell me how to plot geom_text() in the right bottom in each figure.
z_cor <- fit01_varsize2 %>%
filter(!variable1 == "intercept") %>%
group_by(variable1) %>%
# mutate(height = max(value_with) + .3 * sd(value_with)) %>%
ggplot(aes(x = value_without, y = value_with))+
geom_point(aes(color = value), shape = 1)+
# geom_blank(aes(x = 1, y = 1)) +
geom_text(
data = data.frame(variable1 = c("Agricultural_land", "Artificial_land", "Precipitation", "Protected_area",
"RiverLake", "Seashore", "Temperature", "Volcanic_area", "Wasteland"),
label = c("TRUE:FALSE = 694:316", "TRUE:FALSE = 698:312", "TRUE:FALSE = 733:277", "TRUE:FALSE = 864:146",
"TRUE:FALSE = 721:289", "TRUE:FALSE = 739:271", "TRUE:FALSE = 657:353", "TRUE:FALSE = 748:262", "TRUE:FALSE = 707:303")),
aes(x = 0.1, y = 0.1, label = label))+
geom_abline(intercept = 0, slope = 1, linetype = "dashed") +
scale_color_manual(values = c("TRUE" = "salmon", "FALSE" = "steelblue"))+
# geom_smooth(method = "lm",colour= "deepskyblue3")+
# ggpubr::stat_cor(method="pearson", label.y.npc="top", label.x.npc = "center")+
facet_wrap(.~variable1, scales = "free")+
theme(strip.text.x = element_text(size = 20),
axis.title=element_text(size=16),
axis.line = element_line(colour="grey40"),
axis.title.y = element_blank(),
axis.title.x = element_blank(),
legend.position = "bottom",
panel.background = element_rect(fill = "transparent",
colour = "transparent",
size = 0.5, linetype = "solid"),
plot.background = element_rect(fill = "transparent",
colour = "transparent"),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank()
)
[![enter image description here][1]][1]
By setting the aes(x, y) parameters to positive or negative Inf inside geom_text, we can have text labels on the lower right bottom of each facet. The extra hjust and vjust adjust the position of the label so that they would be in the panel.
Here I use the diamonds dataset as an example, and the data for geom_text is called diamonds_label.
library(ggplot2)
diamonds_label <- data.frame(clarity = unique(diamonds$clarity), label = LETTERS[1:8])
ggplot(diamonds, aes(x, y)) +
geom_point() +
facet_wrap(.~clarity, scale = "free") +
geom_text(data = diamonds_label, aes(Inf, -Inf, label = label),
col = "red",
hjust = 1,
vjust = -1)
Created on 2022-05-10 by the reprex package (v2.0.1)

R: Increasing size of dividing lines in ggplot2

In this plot i've to deal with the following problem:
I want to increaze the size of the white dividing lines between the squares. The plot code is:
p <- ggplot(long_form_mittelwerte2, aes(Var1, Var2)) +
geom_tile(aes(fill = Rang), colour = "white")
pneu2 <- p +
scale_fill_gradient(low = "white", high = "blue", limits= c(1, 3), breaks = c(1, 2, 3)) +
geom_text(aes(label = mittelwerte_text2$value), size = 12, color = "gray0") +
theme(axis.title.x = element_blank(),
axis.title.y = element_blank()) +
theme(axis.text.y = element_text(size = 30, color = "black"),
axis.text.x = element_text(size = 30, color = "black")) +
scale_y_discrete(labels = c(h_Filter3x3="3x3", h_Filter3x5="3x5", h_Filter3x9="3x9"),
expand = c(0, 0)) +
scale_x_discrete(expand = c(0, 0)) +
coord_fixed(ratio = 1) +
guides(fill= guide_colorbar(barheight = unit(10, "cm"))) +
theme(legend.text = element_text(size = 30, face = "bold"),
legend.title = element_blank())
If you need data, please let me know. Thanks for helping.
You can set the size and colour arguments inside geom_tile to adjust the space and colour between the tiles:
mtcars %>%
ggplot(aes(cyl, am, fill = mpg)) +
geom_tile(colour = "white", size = 4)

ggplot pie chart choose axes ticks

I would like to know if it's possible to modify the ticks of x axis with a ggplot pie chart.
Here what I can do :
# Some colors
couleurs <- data.frame(
id=seq(1,17,1),
mix=c(c(rep(1,6),rep(2,7),rep(3,4))),
html=c("#A00020","#109618","#388EE4","#C484D1","#FFAA33","#CCCDD0","#004AC5","#F80094","#CB5023","#638995","#33CFCF","#95DC4E","#F7D633","#5C403C","#F72020","#00D96C","#FDE4C5")
)
couleurs$html <- factor(couleurs$html, levels = couleurs$html[order(couleurs$id, decreasing = FALSE)])
# Data
activite <- data.frame(label=c("B to B","B to C","B to B / B to C", "B to B"), cible=c(rep("Externe",3), "Interne"), nb=c(12,9,3,12))
activite$label <- factor(activite$label, levels = activite$label[order(activite$nb[activite$cible=="Externe"], decreasing = TRUE)])
library(plyr)
activite<-ddply(activite,.(cible),transform,pc=(nb/sum(nb))*100)
activite
# Pie chart
library(ggplot2)
ggplot(data = activite, aes(x = "", y = nb, fill = label )) +
geom_bar(stat = "identity", position = position_fill(), width = 1) +
coord_polar(theta= "y", start = 0, direction = -1) +
labs(fill="") +
scale_fill_manual(values=as.character(couleurs$html[1:nrow(activite)]), labels=paste(activite$label,"\t\t\t",sep="")) +
geom_text(aes(label = paste(pc,"%", sep=" ")), size=4, colour = "white", fontface = "bold", position = position_fill(vjust = 0.5)) +
theme(strip.text = element_text(size=20, face = "bold", ), strip.background = element_rect(fill="grey75")) +
theme(panel.background = element_rect(fill = "white")) +
theme(plot.background = element_rect(fill = "grey92")) +
theme(legend.position="bottom", legend.background = element_rect(fill="grey92")) +
theme(legend.key = element_blank()) +
theme(panel.grid.minor = element_blank(), panel.grid.major = element_line(colour = "grey75")) +
theme(axis.text.y = element_blank()) +
theme(axis.ticks.length = unit(0, "mm")) +
theme(axis.title.x = element_blank(),axis.title.y = element_blank()) +
theme(legend.box.spacing = unit(1, "mm")) +
facet_wrap(~ cible)
Here my result:
After several hours of serach, I didn't find a solution to create what I want. The exact same pie chart but with personalised ticks like that :
With these particular conditions :
- do not change the direction of the data in the pie chart, I want it like exactly this
- if possible (but if not possible, it's okay), I would like the ticks' labels not superposed with the axis.
If someone can help me, I would really appreciate.
Here's one solution:
ggplot(data = activite %>%
group_by(cible) %>%
arrange(desc(nb)) %>%
mutate(axis.label = cumsum(nb),
axis.position = cumsum(pc)/100) %>%
mutate(axis.label = ifelse(pc == min(pc),
paste(axis.label, "0", sep = "-"),
axis.label)),
aes(x = 1, y = nb, fill = label )) +
geom_segment(aes(x = 1, xend = 1.6, y = axis.position, yend = axis.position),
colour = "grey75") +
geom_vline(xintercept = 1.6, colour = "grey75") +
geom_bar(stat = "identity", position = position_fill(reverse = T), width = 1) +
coord_polar(theta= "y", start = 0, direction = 1) +
labs(fill="") +
scale_fill_manual(values=as.character(couleurs$html[1:nrow(activite)]), labels=paste(activite$label,"\t\t\t",sep="")) +
geom_text(aes(label = paste(pc,"%", sep=" ")), size=4, colour = "white",
fontface = "bold", position = position_fill(vjust = 0.5, reverse = T)) +
geom_text(aes(x = 1.7, label = axis.label), size = 3,
position = position_fill(reverse = T)) +
theme(strip.text = element_text(size=20, face = "bold", ), strip.background = element_rect(fill="grey75")) +
theme(panel.background = element_rect(fill = "white")) +
theme(plot.background = element_rect(fill = "grey92")) +
theme(legend.position="bottom", legend.background = element_rect(fill="grey92")) +
theme(legend.key = element_blank()) +
theme(panel.grid = element_blank()) +
theme(axis.text = element_blank()) +
theme(axis.ticks = element_blank()) +
theme(axis.title = element_blank()) +
theme(legend.box.spacing = unit(1, "mm")) +
facet_wrap(~ cible)
Explanation:
The sequence in your labels went clockwise, while the direction of the polar coordinates went counter-clockwise. That makes labelling rather troublesome. I switched the direction for polar coordinates, & added reverse = T inside the position adjustment calls for the geoms.
It's hard to assign different axis breaks to different facets of the same plot, so I didn't. Instead, I modified the data to include calculated axis labels / margin positions, added margins via geom_segment / geom_vline, & hid the axis text / ticks in theme().

ggMarginal ignores choord_cartesian. How to change marginal scales?

I'm trying to plot a 2D density plot with ggplot, with added marginal histograms. Problem is that the polygon rendering is stupid and needs to be given extra padding to render values outside your axis limits (e.g. in this case I set limits between 0 and 1, because values outside this range have no physical meaning). I still want the density estimate though, because often it's much cleaner than a blocky 2D heatmap.
Is there a way around this problem, besides scrapping ggMarginal entirely and spending another 50 lines of code trying to align histograms?
Unsightly lines:
Now rendering works, but ggMarginal ignores choord_cartesian(), which demolishes the plot:
Data here:
http://pasted.co/b581605a
dataset <- read.csv("~/Desktop/dataset.csv")
library(ggplot2)
library(ggthemes)
library(ggExtra)
plot_center <- ggplot(data = dataset, aes(x = E,
y = S)) +
stat_density2d(aes(fill=..level..),
bins= 8,
geom="polygon",
col = "black",
alpha = 0.5) +
scale_fill_continuous(low = "yellow",
high = "red") +
scale_x_continuous(limits = c(-1,2)) + # Render padding for polygon
scale_y_continuous(limits = c(-1,2)) + #
coord_cartesian(ylim = c(0, 1),
xlim = c(0, 1)) +
theme_tufte(base_size = 15, base_family = "Roboto") +
theme(axis.text = element_text(color = "black"),
panel.border = element_rect(colour = "black", fill=NA, size=1),
legend.text = element_text(size = 12, family = "Roboto"),
legend.title = element_blank(),
legend.position = "none")
ggMarginal(plot_center,
type = "histogram",
col = "black",
fill = "orange",
margins = "both")
You can solve this problem by using xlim() and ylim() instead of coord_cartesian.
dataset <- read.csv("~/Desktop/dataset.csv")
library(ggplot2)
library(ggthemes)
library(ggExtra)
plot_center <- ggplot(data = dataset, aes(x = E,
y = S)) +
stat_density2d(aes(fill=..level..),
bins= 8,
geom="polygon",
col = "black",
alpha = 0.5) +
scale_fill_continuous(low = "yellow",
high = "red") +
scale_x_continuous(limits = c(-1,2)) + # Render padding for polygon
scale_y_continuous(limits = c(-1,2)) + #
xlim(c(0,1)) +
ylim(c(0,1)) +
theme_tufte(base_size = 15, base_family = "Roboto") +
theme(axis.text = element_text(color = "black"),
panel.border = element_rect(colour = "black", fill=NA, size=1),
legend.text = element_text(size = 12, family = "Roboto"),
legend.title = element_blank(),
legend.position = "none")
ggMarginal(plot_center,
type = "histogram",
col = "black",
fill = "orange",
margins = "both")

Resources