In ggplot/facet_wrap(), how to marke axis Y have different format - ggplot2

In ggplot/facet_wrap(), how to marke axis Y have different format ? Thanks!
library(tidyverse)
test_data <- diamonds
plot_data <- test_data %>% mutate(x_to_price=x/price,
price=price*1000) %>% head(12) %>%
mutate(mseq=1:NROW(.)) %>%
select(price,x_to_price,mseq) %>% gather(key='type',value='amount',- mseq)
plot_data %>% ggplot(aes(x=mseq,y=amount))+geom_line()+geom_point()+
facet_wrap(.~type,scales='free_y')

One option would be the ggh4x package which via facetted_pos_scales allows to set the scales individually for each facet:
library(ggplot2)
library(ggh4x)
ggplot(plot_data, aes(x=mseq,y=amount))+geom_line()+geom_point()+
facet_wrap(.~type,scales='free_y') +
facetted_pos_scales(
y = list(
type == "price" ~ scale_y_continuous(labels = scales::comma_format()),
type == "x_to_price" ~ scale_y_continuous(labels = scales::percent_format())
)
)

Related

I'm trying to forecast an ETS model using data from tsibbledata in R but I'm getting the error message seen at the bottom of the code below

ItalyExp <- global_economy %>%
filter(Country == "Italy")
ItalyExp$Exports <- as.numeric(as.character(ItalyExp$Exports))
ItalyExp %>% autoplot(Exports) + labs(title = "Italian Exports")
etsANNit <- ItalyExp %>%
model(ETS(Exports ~ error("A") + trend("N") + season("N")))
etsANNit
fc <- etsANNit %>%
forecast(h = 10)
This gives the error message:
Warning messages:
1: In mean.default(x, na.rm = TRUE) :
argument is not numeric or logical: returning NA
2: In Ops.factor(left, right) : ‘-’ not meaningful for factors

In ggplot2 , how to align label x text in vertical

In ggplot2 , how to align label x in vertical ? The wished result as attached image .
library(tidyverse)
category <- c("A B C","DF GC","S AA")
amount <- c(3,2,1)
plot_data <- data.frame(category,amount)
plot_data %>% ggplot(aes(x=category,y=amount))+geom_col()
Try this:
library(tidyverse)
category <- c("A B C", "DF GC", "S AA")
amount <- c(3, 2, 1)
plot_data <- data.frame(category, amount)
plot_data %>%
mutate(category = str_wrap(category, 1)) %>%
ggplot(aes(category, amount)) +
geom_col()
Created on 2022-05-07 by the reprex package (v2.0.1)

In ggplot2/plotly ,when I use `geom_bar(stat='identity',position='fill')`,how to change number tip to percent format

In R/ggplot2 ,when I use geom_bar(stat='identity',position='fill'),
the 'sales' tip show '0.80000',how to change it to '80.0%' ?
(I know mutate a new variable use scales::percent(sales),can work in geom_point)
library(tidyverse)
library(plotly)
test_data <- data.frame(category=c('A','B','A','B'),
sub_category=c('a1','b1','a2','b2'),
sales=c(1,2,4,5))
p <- test_data %>%
ggplot(aes(x=category,y=sales,
fill=sub_category))+
geom_bar(stat='identity',position='fill')
ggplotly(p)
One option (and perhaps the easiest one) would be to compute your percentages manually instead of making use of position = "fill" and create the tooltip manually via the text aesthetic which makes it easy to style the numbers, ... as you like:
library(plotly)
test_data <- data.frame(
category = c("A", "B", "A", "B"),
sub_category = c("a1", "b1", "a2", "b2"),
sales = c(1, 2, 4, 5)
)
test_data <- test_data %>%
group_by(category) %>%
mutate(pct = sales / sum(sales))
p <- test_data %>%
ggplot(aes(x = category, y = pct, fill = sub_category)) +
geom_col(aes(text = paste0(
"category: ", category, "<br>",
"sub_category: ", sub_category, "<br>",
"sales: ", scales::percent(pct)
)))
ggplotly(p, tooltip = "text")

How do I get subscript in ggplot2 facet grid labels when I have two faceting variables?

I am trying to change one of the labels in my facet grid to contain some subscript text. I have been looking on stack overflow but none of the solutions work/I cannot understand how others are functioning so cannot apply them to my own scenario
This is my current ggplot function:
FacetGridTest <- tss_profiles %>% group_by(pulldown, Condition, replicate, category) %>%
group_by(pulldown,Condition,category,region_bin, region) %>%
mutate(meannone = mean(none)) %>%
ungroup() %>%
mutate(cond_cat=factor(cond_cat, levels=c("IG Target","IG Non-Target","MH Target","PH Target","MH Non-Target","PH Non-Target"))) %>%
mutate(category=factor(category, levels=c("Target","Non-Target"))) %>%
ggplot() + aes(x=Bin, y=meannone, col=Condition, group=paste(pulldown, Condition, replicate, category)) +
geom_line() +
facet_grid(pulldown~category, scale="free_x") +
theme_bw(base_size = 10) +
theme(legend.text.align = 0) +
labs(y=expression(paste("Read Counts")),
x=expression(paste("Bin"))) +
scale_colour_discrete(name = "Condition", labels = c("A","B","C")) +
geom_vline(xintercept=6000, linetype="dotted") +
annotate("text", x = 1000, y = 8800, label = "TSS", size=3) +
annotate("text", x = 11000, y = 8800, label = "TTS", size=3)
I want to change the "Non-Target" label to "J2L2 Non-Target20+"
Based on what I have seen on stack overflow I have tried doing:
vnames <- list('Target' = 'Target',
'Non-Target' = expression(paste("J" ["2"], "L" ["2"], " Non-Target" ["20"], "+")))
bnames <- list('A' = 'A','B' = 'B')
plot_labeller <- function(variable,value){
if (variable=='category') {
return(vnames[value])
} else if (variable=='pulldown') {
return(bnames[value])
} else {
return(as.character(value))
}
}
tss_profiles %>% group_by(pulldown, Condition, replicate, category) %>%
group_by(pulldown,Condition,category,region_bin, region) %>%
mutate(meannone = mean(none)) %>%
ungroup() %>%
mutate(cond_cat=factor(cond_cat, levels=c("IG Target","IG Non-Target","MH Target","PH Target","MH Non-Target","PH Non-Target"))) %>%
mutate(category=factor(category, levels=c("Target","Non-Target"))) %>%
ggplot() + aes(x=Bin, y=meannone, col=Condition, group=paste(pulldown, Condition, replicate, category)) +
geom_line() +
facet_grid(pulldown~category, scale="free_x", plot_labeller) +
theme_bw(base_size = 10) +
theme(legend.text.align = 0) +
labs(y=expression(paste("Read Counts")),
x=expression(paste("Bin"))) +
scale_colour_discrete(name = "Condition", labels = c("A","B","C")) +
geom_vline(xintercept=6000, linetype="dotted") +
annotate("text", x = 1000, y = 8800, label = "TSS", size=3) +
annotate("text", x = 11000, y = 8800, label = "TTS", size=3)
But this has not worked. I am probably misunderstanding how labellers work. Any help would be much appreciated.
I tried to run both codes but got error that object 'tss_profiles' not found.
Therefore I can just hypothesise that you should remove quotes from the subscript text ([20] instead of what you have - ["20"]).

Colors strips settings in faced-wrap ggplot

To a 3 year old post
ggplot2: facet_wrap strip color based on variable in data set
Baptiste has given the following solution:
d <- data.frame(fruit = rep(c("apple", "orange", "plum", "banana", "pear", "grape")),
farm = rep(c(0,1,3,6,9,12), each=6),
weight = rnorm(36, 10000, 2500),
size=rep(c("small", "large")))
p1 = ggplot(data = d, aes(x = farm, y = weight)) +
geom_jitter(position = position_jitter(width = 0.3),
aes(color = factor(farm)), size = 2.5, alpha = 1) +
facet_wrap(~fruit)
dummy <- ggplot(data = d, aes(x = farm, y = weight))+ facet_wrap(~fruit) +
geom_rect(aes(fill=size), xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) +
theme_minimal()
library(gtable)
g1 <- ggplotGrob(p1)
g2 <- ggplotGrob(dummy)
gtable_select <- function (x, ...)
{
matches <- c(...)
x$layout <- x$layout[matches, , drop = FALSE]
x$grobs <- x$grobs[matches]
x
}
panels <- grepl(pattern="panel", g2$layout$name)
strips <- grepl(pattern="strip-t", g2$layout$name)
g2$layout$t[panels] <- g2$layout$t[panels] - 1
g2$layout$b[panels] <- g2$layout$b[panels] - 1
new_strips <- gtable_select(g2, panels | strips)
library(grid)
grid.newpage()
grid.draw(new_strips)
gtable_stack <- function(g1, g2){
g1$grobs <- c(g1$grobs, g2$grobs)
g1$layout <- transform(g1$layout, z= z-max(z), name="g2")
g1$layout <- rbind(g1$layout, g2$layout)
g1
}
## ideally you'd remove the old strips, for now they're just covered
new_plot <- gtable_stack(g1, new_strips)
grid.newpage()
grid.draw(new_plot)
(I have just updated the "strip-t" pattern and opened the grid library as it was suggested in the old post)
I repost this because it's an old brillant stuff and I want to use it myself for a presentation.
I'm a beginner in ggplot and this could also help me for various scripts.
Here are my questions :
- How is it possible to choose the color and not to give the same blue and red please? In my script, I have 3 colors to set, and I hope it can be less agressive. Is it possible to do it ?
- Another question, is it possible to integrate this in the legend, i.e to know what are this colors refering ?
Many thanks
you can change the strip colours with the fill scale in the dummy plot. Combining the legends is a bit tricky, but here's a starting point.
library(ggplot2)
library(gtable)
library(gridExtra)
library(grid)
gtable_stack <- function(g1, g2){
g1$grobs <- c(g1$grobs, g2$grobs)
g1$layout <- transform(g1$layout, z= z-max(z), name="g2")
g1$layout <- rbind(g1$layout, g2$layout)
g1
}
gtable_select <- function (x, ...)
{
matches <- c(...)
x$layout <- x$layout[matches, , drop = FALSE]
x$grobs <- x$grobs[matches]
x
}
d <- data.frame(fruit = rep(c("apple", "orange", "plum", "banana", "pear", "grape")),
farm = rep(c(0,1,3,6,9,12), each=6),
weight = rnorm(36, 10000, 2500),
size=rep(c("small", "large")))
p1 = ggplot(data = d, aes(x = farm, y = weight)) +
geom_jitter(position = position_jitter(width = 0.3),
aes(color = factor(farm)), size = 2.5, alpha = 1) +
facet_wrap(~fruit)
dummy <- ggplot(data = d, aes(x = farm, y = weight))+ facet_wrap(~fruit) +
geom_rect(aes(fill=size), xmin=-Inf, xmax=Inf, ymin=-Inf, ymax=Inf) +
theme_minimal() + scale_fill_brewer(palette = "Pastel2")
g1 <- ggplotGrob(p1)
g2 <- ggplotGrob(dummy)
# extract legends
leg <- g1$grobs[[grep("guide-box", g1$layout$name)]]
dummy_leg <- g2$grobs[[grep("guide-box", g2$layout$name)]]
combined_leg <- rbind.gtable(leg, dummy_leg)
g1$grobs[[grep("guide-box", g1$layout$name)]] <- combined_leg
# move dummy panels one cell up
panels <- grepl(pattern="panel", g2$layout$name)
strips <- grepl(pattern="strip-t", g2$layout$name)
g2$layout$t[panels] <- g2$layout$t[panels] - 1
g2$layout$b[panels] <- g2$layout$b[panels] - 1
new_strips <- gtable_select(g2, panels | strips)
# stack new strips on top of gtable
# ideally you'd remove the old strips, for now they're just covered
new_plot <- gtable_stack(g1, new_strips)
grid.newpage()
grid.draw(new_plot)