I have an example code below. I have built a figure with ggplot and it is almost there, but I would like to add an additional curve across all facets from y. The final output should look like the image attached. I'm not sure how I would do this.
x <- iris[-1:-3]
bw <- 1
nbin <- 100
y <- head(iris, 50)[2]
ggplot(x, aes(x = Petal.Width)) +
geom_density(aes(y = bw *..count.., fill = Species), size = 1, alpha = 0.4) +
facet_wrap(~Species)+
scale_x_continuous(labels = scales::math_format(10^.x), limits = c(0, 5), expand = c(0,0)) +
scale_y_continuous(expand = c(0,0), limits = c(0, NA)) +
annotation_logticks(sides = "b", short=unit(-1,"mm"), mid=unit(-2,"mm"), long=unit(-3,"mm")) +
coord_cartesian(clip='off') + theme(panel.background = element_blank(),
panel.border = element_rect(colour = "black", fill=NA))
Does this do what you are looking to achieve?
I'm sure there are better ways; basically I've generated three versions of the y data and shuffled the grouping variables to allow ggplot's facet_wrap and fill to manage the appearance.
It would be great if there is way to make one set of data appear in all facets without this repetition.
library(ggplot2)
library(dplyr)
library(tidyr)
x1 <-
x %>%
mutate(var = "Petal width") %>%
rename(val = Petal.Width)
df <-
y %>%
mutate(var = "Sepal width",
spp1 = "setosa",
spp2 = "versicolor",
spp3 = "virginica") %>%
pivot_longer(cols = starts_with("spp"), names_to = "temp", values_to = "Species") %>%
select(-temp) %>%
rename(val = Sepal.Width )%>%
bind_rows(x1) %>%
mutate(g1 = case_when(var == "Sepal width" ~ "all species: sepal width",
TRUE ~ paste0(Species, ": petal width")))
ggplot(df, aes(x = val)) +
geom_density(aes(y = bw *..count.., fill = g1), size = 1, alpha = 0.4) +
facet_wrap(~Species)+
scale_x_continuous(labels = scales::math_format(10^.x), limits = c(0, 5), expand = c(0,0)) +
scale_y_continuous(expand = c(0,0), limits = c(0, NA)) +
annotation_logticks(sides = "b", short=unit(-1,"mm"), mid=unit(-2,"mm"), long=unit(-3,"mm")) +
coord_cartesian(clip='off') + theme(panel.background = element_blank(),
panel.border = element_rect(colour = "black", fill=NA))
Created on 2020-07-01 by the reprex package (v0.3.0)
Related
Is it possible to make this graph with ggplot, ordering the graph by the variable "t" in ascending order, distinguishing each "t" according to status (black or white circle, it can be another marker...) and if possible the variable "id " on the ordinate axis.
Id<- c(1,2,3,4)
t<- c(10,5,20,15)
status<- c(0,1,0,1)
df<- data.frame(Id, t, status)
Maybe you want something like this using geom_segment for the lines with geom_vline for the vertical lines. Using shape and fill aesthetics to fill the points with "black" and "white" per status. You can use the following code:
Id<- c(1,2,3,4)
t<- c(10,5,20,15)
status<- c(0,1,0,1)
df<- data.frame(Id, t, status)
library(ggplot2)
library(dplyr)
library(forcats)
df %>%
mutate(Id = as.factor(Id),
status = as.factor(status)) %>%
ggplot(aes(x = t, y = fct_reorder(Id, t, .desc = TRUE), shape = status, fill = status)) +
geom_point() +
geom_segment(aes(x = 0, xend = t, y = Id, yend = Id)) +
geom_vline(xintercept=c(t),linetype="dotted", alpha = 0.4) +
scale_shape_manual(values=c(21, 21), name = "shapes!") +
scale_fill_manual(values=c("black", "white")) +
scale_x_continuous(expand = c(0, 0), limits = c(0, 25)) +
labs(x = "", y = "Id") +
theme_bw() +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
legend.position = "none",
axis.title.y = element_text(angle=0))
Created on 2022-07-25 by the reprex package (v2.0.1)
My ggplot2 legend is not colouring correctly - it is appearing in all black rather than the colours of my plot. I have reproduced this error in the iris dataset.
iris <- iris %>%
mutate(
Size = case_when(
`Sepal.Length` < 5.4 ~ "Small",
`Sepal.Length` > 5.4 ~ "Big"
))
iris_mapping <- aes_string(
fill = paste0("`Species`"),
shape = paste0("`Size`")
)
my_plot <-
ggplot(iris,
aes_string(
x = paste0("`Petal.Length`"),
y = paste0("`Petal.Width`"))) +
geom_point(iris_mapping,
size = 4, alpha = 0.9, color = "black") +
theme_bw() +
theme(
plot.title = element_text(hjust = 0.5),
legend.text = element_text(family = "mono", face = "bold")) +
scale_fill_manual(
values = fgplots::brew_fg_colors(length(unique(iris$Species))),
name = "Species") +
scale_shape_manual(name = "Size",
values = c(21, 22))+
xlab("`Petal.Length`") +
ylab("`Petal.Width`")
Does anyone know why this is happening / how I can get the legend colour to match the plot colouring?
I have the following randomly created data:
t<- matrix(sample.int(100,size=20,replace=TRUE),nrow=12,ncol=20)
a = list()
b = list()
for (x in (1:20) ) b[[x]] <- paste0("X_", x)
for (x in (1:12) ) a[[x]] <- paste0("X", x)
row.names(t) <- rbind(a)
colnames(t) <- rbind(b)
t <- as.data.frame(t)
Here t is a hypothetical two way table of frequencies, I am trying to plot a graph like the one given here using ggplot2
I am not sure how can I make t in such a way that it can be used in ggplot2 code given in the link above. Also, I appreciate if you can provide suggestions on how to visualize a larger two way table, for instance, if dimension of t grows to something 30 x 50.
Here's one approach:
EDIT to show values underneath:
t %>%
rownames_to_column() %>%
pivot_longer(-rowname) %>%
mutate(across(rowname:name, fct_inorder)) %>%
ggplot(aes(x = 1, y = value)) +
geom_col() +
geom_text(aes(x = 1, y = 0, label = value), vjust = 1.1, size = 2.5) +
scale_x_continuous(breaks = NULL) +
scale_y_continuous(breaks = NULL) +
facet_grid(rowname~name) +
coord_cartesian(clip = "off")
Here is a modification of Jon Springs code with some "layout" tweaking:
library(tidyverse)
df %>%
rownames_to_column() %>%
pivot_longer(-rowname) %>%
mutate(across(rowname:name, fct_inorder)) %>%
ggplot(aes(x = 1, y = value, fill=value)) +
geom_col(width = 0.5) +
geom_text(aes(x = 1, y = 0, label = value), vjust = 1.1, size = 2.5) +
scale_x_continuous(breaks = NULL) +
scale_y_continuous(breaks = NULL) +
facet_grid(rowname~name, switch = "both") +
coord_cartesian(clip = "off") +
theme_void() +
theme(strip.background = element_blank(),
strip.text.y.left = element_text(angle = 0),
panel.spacing = unit(1, "lines"),
strip.placement = "outside",
strip.switch.pad.grid = unit(0.2, "in"))+
guides(fill="none")
I have a matrix with many zero elements. The column names are labeled on the horizontal axis. I'd like to show explictly the nonzero elements as the bias from the vertical line for each column.
So how should construct a figure such as the example using ggplot2?
An example data can be generated as follow:
set.seed(2018)
N <- 5
p <- 40
dat <- matrix(0.0, nrow=p, ncol=N)
dat[2:7, 1] <- 4*rnorm(6)
dat[4:12, 2] <- 2.6*rnorm(9)
dat[25:33, 3] <- 2.1*rnorm(9)
dat[19:26, 4] <- 3.3*rnorm(8)
dat[33:38, 5] <- 2.9*rnorm(6)
colnames(dat) <- letters[1:5]
print(dat)
Here is another option using facet_wrap and geom_col with theme_minimal.
library(tidyverse)
dat %>%
as.data.frame() %>%
rowid_to_column("row") %>%
gather(key, value, -row) %>%
ggplot(aes(x = row, y = value, fill = key)) +
geom_col() +
facet_wrap(~ key, ncol = ncol(dat)) +
coord_flip() +
theme_minimal()
To further increase the aesthetic similarity to the plot in your original post we can
move the facet strips to the bottom,
rotate strip labels,
add "zero lines" in matching colours,
remove the fill legend, and
get rid of the x & y axis ticks/labels/title.
library(tidyverse)
dat %>%
as.data.frame() %>%
rowid_to_column("row") %>%
gather(key, value, -row) %>%
ggplot(aes(x = row, y = value, fill = key)) +
geom_col() +
geom_hline(data = dat %>%
as.data.frame() %>%
gather(key, value) %>%
count(key) %>%
mutate(y = 0),
aes(yintercept = y, colour = key), show.legend = F) +
facet_wrap(~ key, ncol = ncol(dat), strip.position = "bottom") +
coord_flip() +
guides(fill = FALSE) +
theme_minimal() +
theme(
strip.text.x = element_text(angle = 45),
axis.title = element_blank(),
axis.text = element_blank(),
axis.ticks = element_blank())
It would be much easier if you can provide some sample data. Thus I needed to create them and there is no guarantee that this will work for your purpose.
set.seed(123)
# creating some random sample data
df <- data.frame(id = rep(1:100, each = 3),
x = rnorm(300),
group = rep(letters[1:3], each = 100),
bias = sample(0:1, 300, replace = T, prob = c(0.7, 0.3)))
# introducing bias
df$bias <- df$bias*rnorm(nrow(df))
# calculate lower/upper bias for errorbar
df$biaslow <- apply(data.frame(df$bias), 1, function(x){min(0, x)})
df$biasupp <- apply(data.frame(df$bias), 1, function(x){max(0, x)})
Then I used kind of hack to be able to print groups in sufficient distance to make them not overlapped. Based on group I shifted bias variable and also lower and upper bias.
# I want to print groups in sufficient distance
df$bias <- as.numeric(df$group)*5 + df$bias
df$biaslow <- as.numeric(df$group)*5 + df$biaslow
df$biasupp <- as.numeric(df$group)*5 + df$biasupp
And now it is possible to plot it:
library(ggplot2)
ggplot(df, aes(x = x, col = group)) +
geom_errorbar(aes(ymin = biaslow, ymax = biasupp), width = 0) +
coord_flip() +
geom_hline(aes(yintercept = 5, col = "a")) +
geom_hline(aes(yintercept = 10, col = "b")) +
geom_hline(aes(yintercept = 15, col = "c")) +
theme(legend.position = "none") +
scale_y_continuous(breaks = c(5, 10, 15), labels = letters[1:3])
EDIT:
To incorporate special design you can add
theme_bw() +
theme(axis.text.y = element_blank(),
axis.ticks.y = element_blank(),
axis.title.y = element_blank(),
axis.text.x = element_text(angle = 45, vjust = 0.5, hjust = 1),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank())
to your plot.
EDIT2:
To incorporate several horizontal lines, you can create different dataset:
df2 <- data.frame(int = unique(as.numeric(df$group)*5),
gr = levels(df$group))
And use
geom_hline(data = df2, aes(yintercept = int, col = gr))
instead of copy/pasting geom_hline for each group level.
I am trying to produce a heatmap in ggplot. I want each group to have different color gradient, but don't know how to do that. My current code looks like this:
## dummy data -----------------------------------------------------------------------------
data <- data.frame(
group = sample(c("Direct Patient Care", "Indirect Patient Care", "Education", "Rounds", "Handoff", "Misce"), 30, replace = T),
pct = rnorm(30, mean = 50, sd = 8)
)
## generate group id
data <- data %>%
group_by(group) %>%
mutate(id = row_number())
data$grpid <- with(data, ifelse(group == "Direct Patient Care", 1, ifelse(group == "Indirect Patient Care", 2,
ifelse(group == "Education", 3,
ifelse(group == "Rounds", 4,
ifelse(group == "Handoff", 5,6 ))))))
## draw graph ------------------------------------------------------------------------------
library(ggplot2)
p <- ggplot(data, aes(x=id, y=group, fill = pct)) +
theme(panel.background = element_rect(fill = "white", colour = "grey50"), aspect.ratio = 0.4) +
theme(panel.grid.major = element_blank(),
panel.grid.minor = element_blank()
)+
# guides(fill = guide_legend("Time, %")) +
geom_tile() +
scale_x_continuous (name = " ", breaks = seq(1, 8, by = 1)) +
scale_y_discrete(name = " ") +
theme(axis.text.x = element_text(angle = 0,hjust = 1,vjust = 1), plot.title = element_text(hjust = 0.5) ) +
ggtitle("Heatmap of time spent doing activities across 194 shifts")
p + scale_fill_gradient2(low = "white", high = "red", limits = c(0, 80), breaks = c(0, 10, 20, 30, 40, 50, 60, 70), guide = guide_legend("Time, %")) ## change the color theme ##
And the resulting figure looks like this:
How can I change the color theme for each group, like red for 'Rounds', blue for 'Misce', green for 'Handoff' etc...
Many thanks!
You can do this by creating your own rescaled value in your data and then slightly "hacking" the alpha aesthetic combined with the fill aesthetic:
library(tidyverse)
data %>%
group_by(group) %>%
mutate(rescale = scales::rescale(pct)) %>%
ggplot(., aes(x = factor(id), y = group)) +
geom_tile(aes(alpha = rescale, fill = group), color = "white") +
scale_alpha(range = c(0.1, 1))
First we create a new column called rescale which rescales the pct from 0 to 1 then you force the scale_alpha(range = c(0, 1)) [note, in this case I used c(0.1, 1) so that you can still "see" the zero points.
Finally, you probably want to remove the guides:
data %>%
group_by(group) %>%
mutate(rescale = scales::rescale(pct)) %>%
ggplot(., aes(x = factor(id), y = group)) +
geom_tile(aes(alpha = rescale, fill = group), color = "white") +
scale_alpha(range = c(0.1, 1)) +
theme(legend.position = "none")
N.B. by using aes(x = factor(id)... you can get around manually setting your x-axis since in this case it appears you want to treat it as a factor not a numeric scale.
Finally, if you really want to get fancy, you could double-encode the axis.text.y colors to that of the levels of your factor (i.e., data$group) variable:
data %>%
group_by(group) %>%
mutate(rescale = scales::rescale(pct)) %>%
ggplot(., aes(x = factor(id), y = group)) +
geom_tile(aes(alpha = rescale, fill = group), color = "white") +
scale_alpha(range = c(0.1, 1)) +
theme(legend.position = "none",
axis.text.y = element_text(color = scales::hue_pal()(length(levels(data$group)))),
axis.ticks = element_blank()) +
labs(x = "", y = "")