How to create a partial italic axis title in ggplot - r

I am trying to make part of my title in italics (M.alfredi) but cant figure out how? Can anyone help? Thanks.
library(tidyverse)
library(reshape2)
dat <- read_xlsx("ReefPA.xlsx")
names(dat) <- str_replace_all(names(dat), " ", "_")
dat1 <- dat d
at1$Date <- format(dat1$Date, "%Y/%m")
dat1 %>%
group_by(Date) %>%
tally() %>%
filter(Date > '2014-01-01') %>%
ggplot() +
geom_bar(aes(x = Date, y = n), stat = 'identity') +
theme(axis.text.x = element_text(angle = 90, vjust = 0.5, hjust = 1)) +
ylab("Total Number of M.alfredi Encounters Per Month")

You can use plotmath expressions to label your axis. There is no sample data here, but this mock-up should suffice:
ggplot(data = data.frame(x = 1:30, y = round(runif(30, 20, 50))), aes(x, y)) +
geom_col() +
labs(y = expression("Total Number of "~italic(M.alfredi)~"Encounters Per Month"))

Related

How do I nudge geom text labels to the right with a chart with ggplotly?

I'd like to set the text on each of the columns in ggplot and they're bunching up altogether
this is my code
set.seed(1)
gg <-
iris[sample(300, 50), ] %>%
ggplot(aes(Species, Sepal.Length, label = Sepal.Length, fill = as.factor(Sepal.Width > 3))) +
geom_col(position = "dodge2") +
geom_text(position=position_dodge(width = .7),
vjust=-0.25)
ggplotly(gg)
Maybe I would suggest using same position style in geom_col() and geom_text():
library(plotly)
library(ggplot2)
set.seed(1)
#Plot
gg <-
iris[sample(300, 50), ] %>%
ggplot(aes(Species, Sepal.Length, label = Sepal.Length, fill = as.factor(Sepal.Width > 3))) +
geom_col(position = position_dodge2(0.9)) +
geom_text(position=position_dodge2(width = .9),
vjust=-0.5)
#Transform
ggplotly(gg)
Output:
With shared data, try this, you have to format the date to have dodged labels:
library(dplyr)
library(ggplot2)
library(plotly)
#Code
gg <- df %>%
mutate(first_month=factor(format(first_month,'%b-%m'),
levels = unique(format(first_month,'%b-%m')),
ordered = T)) %>%
ggplot(aes(x=first_month, y=customers,
label = customers, fill = plan_id,group=plan_id)) +
geom_bar(stat='identity',position = 'dodge')+
geom_text(aes(group=plan_id),position = position_dodge(0.9),vjust = -0.5)
#Plot 2
ggplotly(gg)
Output:

How to do a bar graphic with multiple columns out of an excel archive?

How can I make a graphic bar using barplot() or ggplopt() of an excel archive that has 83 columns?
I need to plot every column that has a >0 value on ich raw. (ich column represents a gene function and I need to know how many functions there is on ich cluster).
Iwas trying this,but it didn't work:
ggplot(x, aes(x=Cluster, y=value, fill=variable)) +
geom_bar(stat="bin", position="dodge") +
theme_bw() +
ylab("Funções no cluster") +
xlab("Cluster") +
scale_fill_brewer(palette="Blues")
Link to the excel:
https://github.com/annabmarques/GenesCorazon/blob/master/AllclusPathwayEDIT.xlsx
What about a heatmap? A rough example:
library(dplyr)
library(tidyr)
library(ggplot2)
library(openxlsx)
data <- read.xlsx("AllclusPathwayEDIT.xlsx")
data <- data %>%
mutate(cluster_nr = row_number()) %>%
pivot_longer(cols = -c(Cluster, cluster_nr),
names_to = "observations",
values_to = "value") %>%
mutate(value = as.factor(value))
ggplot(data, aes(x = cluster_nr, y = observations, fill = value)) +
geom_tile() +
scale_fill_brewer(palette = "Blues")
Given the large number of observations consider breaking this up into multiple charts.
It's difficult to understand exactly what you're trying to do. Is this what you're trying to achieve?
#install.packages("readxl")
library(tidyverse)
library(readxl)
read_excel("AllclusPathwayEDIT.xlsx") %>%
pivot_longer(!Cluster, names_to = "gene_counts", values_to = "count") %>%
mutate(Cluster = as.factor(Cluster)) %>%
ggplot(aes(x = Cluster, y = count, fill = gene_counts)) +
geom_bar(position="stack", stat = "identity") +
theme(legend.position = "right",
legend.key.size = unit(0.4,"line"),
legend.text = element_text(size = 7),
legend.title = element_blank()) +
guides(fill = guide_legend(ncol = 1))
ggsave(filename = "example.pdf", height = 20, width = 35, units = "cm")

ggplot2 to create multiple plots but without a facet_wrap

I want to plot four independent (in 2 rows and 2 columns) plots, each with a different flipped x axis. I have used ggplot with a face_wrap but this approach doesn't give each plot its own flipped x-axis labels.
Is there a way to achieve my goal in ggplot2?
library(tidyverse)
data <- read_csv('https://raw.githubusercontent.com/rnorouzian/e/master/surv.csv')
names(data)[2:5] <- c("Representation", "Solidification", "Application", "Confidence")
data %>%
pivot_longer(cols = -id) %>%
mutate(name = name,
value = str_wrap(value, 50)) %>%
ggplot() +
geom_bar(aes(value, fill = name), show.legend = FALSE) +
facet_wrap(.~name) +
coord_flip() +
labs(y = "Students", x = "") +
theme(axis.text.y = element_text(size=8))
Adding scales = 'free_y' to your original code.
Edit: add code to manually change order of the levels.
level_order <- c("Neutral",
"Agree",
"Strongly Agree",
"The assignment gave me a great opportunity to\napply what I learned",
"The assignment gave me an opportunity to apply\nwhat I learned",
"The assignment helped me solidify the key concepts",
"The assignment highly helped me solidify the key\nconcepts",
"The assignment highly reflected the class\ninstructions",
"The assignment reflected the class instructions",
"The assignment somewhat reflected the class\ninstructions")
data %>%
pivot_longer(cols = -id) %>%
mutate(name = name,
value = str_wrap(value, 50),
value = factor(value, levels = level_order)) %>%
ggplot() +
geom_bar(aes(value, fill = name), show.legend = FALSE) +
facet_wrap(.~name, scales = 'free_y') +
coord_flip() +
labs(y = "Students", x = "") +
theme(axis.text.y = element_text(size=8))
I would suggest next approach:
#Code
library(tidyverse)
data <- read_csv('https://raw.githubusercontent.com/rnorouzian/e/master/surv.csv')
names(data)[2:5] <- c("Representation", "Solidification", "Application", "Confidence")
The option 1 would be adjusting facet_wrap():
#Option 1
data %>%
pivot_longer(cols = -id) %>%
mutate(name = name,
value = str_wrap(value, 50)) %>%
ggplot() +
geom_bar(aes(value, fill = name), show.legend = FALSE) +
facet_wrap(.~name,scales='free') +
labs(y = "Students", x = "") +
theme(axis.text.y = element_text(size=8))
And the second option would be create a list and a function for the plots:
#Option 2
data2 <- data %>%
pivot_longer(cols = -id) %>%
mutate(name = name,
value = str_wrap(value, 50))
#Split
LData2 <- split(data2,data2$name)
#Now function to plot
myfun <- function(x)
{
mplot <- ggplot(x,aes(value, fill = name)) +
geom_bar(show.legend = FALSE) +
labs(y = "Students", x = "") +
theme(axis.text.y = element_text(size=8))+
ggtitle(unique(x$name))
return(mplot)
}
#Apply
Lplots <- lapply(LData2,myfun)
Some example output:
#Example
Lplots[[1]]
Or using patchwork with wrap_plots() in the list:
library(patchwork)
#Code
wrap_plots(Lplots)
Output:
Or changing the axis orientation and using patchwork:
#Now function to plot 2
myfun <- function(x)
{
mplot <- ggplot(x,aes(value, fill = name)) +
geom_bar(show.legend = FALSE) +
labs(y = "Students", x = "") +
coord_flip()+
theme(axis.text.y = element_text(size=8))+
ggtitle(unique(x$name))
return(mplot)
}
#Apply
Lplots <- lapply(LData2,myfun)
#Wrap
wrap_plots(Lplots)
Output:

Rename ordered x-axis labels in faceted ggplot

I'm trying to rename faceted, ordered, x-axis tick marks in ggplot().
library(ggplot2)
library(dplyr)
set.seed(256)
myFun <- function(n = 5000) {
a <- do.call(paste0, replicate(5, sample(LETTERS, n, TRUE), FALSE))
paste0(a, sprintf("%04d", sample(9999, n, TRUE)), sample(LETTERS, n, TRUE))
}
n <- 15
dat <- data.frame(category = sample(letters[1:2], n, replace = T),
name = myFun(n),
perc = sample(seq(0, 1, by = 0.01), n, replace = TRUE))
to_plot <-
dat %>%
group_by(category) %>%
arrange(category, desc(perc)) %>%
top_n(5, perc)
Plotting this gets me
to_plot %>%
ggplot(aes(x = name, y = perc)) +
geom_bar(stat = "identity") +
facet_wrap(~category, scales = "free_y") +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
which is unordered and not what I want at all, so I do some ordering by adding a "dummy" column of row_number()
to_plot %>%
mutate(row_number = row_number()) %>%
ungroup() %>%
mutate(row_number = row_number %>% as.factor()) %>%
ggplot(aes(x = row_number, y = perc)) +
geom_bar(stat = "identity") +
facet_wrap(~category, scales = "free_y") +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
This gets me close, but I still need to change the names on the x-axis so I add:
scale_x_discrete(name = "name", labels = str_wrap(to_plot %>% pull(name), 3))
but this only repeats the first facet group across both facets, even though the data in each plot is correct
I've also tried just ordering everything sequentially and allowing both axes to be free in the facet_wrap() fx, but that doesn't seem to work either:
new_plot <-
dat %>%
group_by(category) %>%
arrange(category, desc(perc)) %>%
ungroup() %>%
mutate(row_number = row_number() %>% as.factor())
new_plot %>%
ggplot(aes(x = row_number, y = perc)) +
geom_bar(stat = "identity") +
scale_x_discrete(name = "name", labels = new_plot %>% pull(name)) +
facet_wrap(~category, scales = "free") +
theme(axis.text.x = element_text(angle = 45, hjust = 1))
How can I label the x-axis tick-marks in multiple facet_wrap() plots independently of one another? I feel like I'm missing something pretty basic here, but I can't figure out what it is.
to_plot %>%
ggplot(aes(x = name %>% forcats::fct_reorder(-perc), y = perc)) +
geom_bar(stat = "identity") +
facet_wrap(~category, scales = "free") +
theme(axis.text.x = element_text(angle = 45, hjust = 1))

Use count in the y-axis but percentages and counts as labels

I am trying to create a bar chart in R from a data frame, which has counts in the y-axis but displays as labels a concatenation of percentages and counts.
My data frame looks as below:
ID Response
1 No
2 Yes
3 No
.. ..
The end result I would like to have would be a chart as the one below
This should get you going:
library(tidyverse)
df %>%
group_by(Response) %>%
summarise(count = n()) %>%
mutate(Label = paste0(count, " - ", round(count / sum(count) * 100, 2), "%")) %>%
ggplot(aes(x = Response, y = count)) +
geom_bar(stat = 'identity', fill = 'lightblue') +
geom_text(aes(label = Label)) +
theme_minimal()
A solution as above can be to create a Label column which you can then pass to geom_text if needed.
A dummy data frame:
df <- data.frame(
ID = c(1:100),
Response = c(rep("Yes", 60), rep("No", 40))
)
I'd try something like the below. It's awesome that you're using summarize and mutate; I guess by habit I sometimes use base functions like table.
library(tidyverse)
resps<-sample(c("yes", "no"), 850, replace=T)
percents<-round(100*table(resps)/length(resps),2)
counts<-as.numeric(table(resps))
plotdat<-data.frame(percents, counts=counts, response=rownames(percents))
plotdat %>% ggplot(aes(response, counts)) +
geom_col()+
geom_text(aes(y=counts+10), label=paste(percents,"% ", counts))
labs(y="respondents")+
theme_classic()
This is a helpful solution from another question on SO:
library(ggplot2)
library(scales)
data.frame(response = sample(c("Yes", "No"), size = 100, replace = T, prob = c(0.4, 0.6))) %>%
ggplot(aes(x = response)) +
geom_bar(aes(y = (..count..)/sum(..count..))) +
geom_text(aes(y = ((..count..)/sum(..count..)),
label = scales::percent((..count..)/sum(..count..))), stat = "count", vjust = -0.25) +
scale_y_continuous(labels = percent) +
labs(title = "Proportion of Responses", y = "Percent", x = "Response")

Resources