ggplot: how to remove unused factor levels from a facet?
Setting scales = free in facet grid will do the trick:
facet_grid( ~ fac, scales = "free")
removing unused factors from facet_grid with row and column specified
There are no unused factors in your sample data and the arguments are not giving you what you desire. Possible startup workaround can be:
# Your script
p <- ggplot(test_data, aes(x = position, y = factor(name))) +
geom_tile(aes(fill = base)) +
scale_fill_viridis_d() +
theme_bw() +
theme(
axis.title.y=element_blank(),
axis.text.y=element_blank(),
legend.title=element_blank(),
axis.title.x=element_text(margin = margin(t = 15)),
panel.grid=element_blank()
)
p + coord_flip() + facet_wrap(ntile ~ sample, scales = "free")
output
Removing Unused Factors from a Facet in ggplot2
I think all you need is scales = "free_y"
:
p0 = ggplot(mydf, aes(x = x, y = y)) +
geom_point() +
facet_wrap(~ cat, ncol = 1,scales = "free_y")
p0
Removing unused levels in ggplot boxplot with facets AND flipped coordinates?
It is an issue of ggplot2: coord_flip and free scales don't work
You can read a discussion about this matter here:
How to drop unused factors in faceted R ggplot boxplot?
In ggplot2, coord_flip and free scales don't work together
Exclude unused factor levels in each facet in ggplot
This is a bit of a workaround but it gives a plot a plot which seems to meet your basic objectives. geom_bar
is replaced with geom_seqment
because that seems closer to what you're plotting and avoids the complications of coord_flip
. The order of the bars is determined by the rank of vars
in each group
. The y axis labels can't be specified directly but you can use geom_text
to place the proper names
values next to the y axis so these act as labels. Also, I switched the facet label to the left side which seemed to improve the overall appearance of the facet and y axis labels.
set.seed(177)
df <- data.frame(vars=c(rnorm(3),rnorm(3,2,1), rnorm(3,1,1)),
names=c("a","b","c","a","d","b","c","a","f"),
groups=c(rep("x",3),rep("y",3),rep("z",3)))
library(ggplot2)
sp1 <- ggplot(data=transform(df, ranked=ave(vars, groups, FUN=rank)),
aes( x=vars, y=ranked))
sp1 <- sp1 + geom_segment( aes( xend = 0, yend = ranked), size=10)
sp1 <- sp1 + geom_text( aes( x = min(vars), y= ranked, label = names), hjust= 4)
sp1 <- sp1 + scale_y_discrete(label=NULL)
sp1 <- sp1 + theme_bw()
sp1 <- sp1 + facet_grid( groups ~ ., scales="free", switch="y")
plot(sp1)
Plot looks like
ggplot2: Deleting facets of unused factor level combinations from a plot (facet_grid)
In ggplot2 2.2.0, the names of the grobs in a plot have changed.
library(ggplot2)
library(grid)
d <- data.frame('factor_1' = factor(c('a', 'a', 'b')),
'factor_2' = factor(c('1', '2', '1')),
x = 1:3, y = 1:3)
p = ggplot(data = d, mapping = aes(x = x, y = y)) +
geom_point() +
facet_grid(facets = factor_1 ~ factor_2, drop = TRUE)
# Get ggplot grob
g = ggplotGrob(p)
# Get the layout dataframe.
# Note the names.
# You want to remove "panel-2-2"
g$layout
# gtable::gtable_show_layout(g) # Might also be useful
# Remove the grobs
# The grob needs to be remove,
# and the relevant row in the layout data frame needs to be removed
pos <- grepl(pattern = "panel-2-2", g$layout$name)
g$grobs <- g$grobs[!pos]
g$layout <- g$layout[!pos, ]
# Alternatively, replace the grobs with the nullGrob
g = ggplotGrob(p)
pos <- grep(pattern = "panel-2-2", g$layout$name)
g$grobs[[pos]] <- nullGrob()
# If you want, move the axis
# g$layout[g$layout$name == "axis-b-2", c("t", "b")] = c(8, 8)
# Draw the plot
grid.newpage()
grid.draw(g)
The answer in your link would need to be modified something like this:
n <- 1000
df <- data.frame(x = runif(n), y=rnorm(n), label = sample(letters[1:7],
size = n, replace = TRUE), stringsAsFactors=TRUE)
df$label.new <- factor(df$label, levels=sort(c(""," ",levels(df$label))))
p <- ggplot(df, aes(x=x, y=y)) + geom_point() +
facet_wrap(~ label.new, ncol=3,drop=FALSE)
g = ggplotGrob(p)
g$layout # Note the names and their positions (t, b, l, r)
# gtable::gtable_show_layout(g) # Might also be useful
pos <- g$layout$name %in% c("panel-1-1", "panel-1-2", "strip-t-1-1", "strip-t-2-1")
g$grobs <- g$grobs[!pos]
g$layout <- g$layout[!pos, ]
# Or replace the grobs with the nullGrob
g = ggplotGrob(p)
pos <- g$layout$name %in% c("panel-1-1", "panel-1-2", "strip-t-1-1", "strip-t-2-1")
g$grobs[pos] <- list(nullGrob())
# Move the axis
g$layout[g$layout$name == "axis-l-1-1", c("l", "r")] = c(10,10)
grid.newpage()
grid.draw(g)
Drop unused levels in facet_wrap in ggplot2
Specify scales = "free_y"
figure.gg = ggplot(data = df, aes(x = group1, y = est, ymin = lwr, ymax = upr)) +
geom_point(position = position_dodge(width = 0.5)) +
geom_errorbar(position = position_dodge(width = 0.5), width = 0.1) +
coord_flip() +
# Facet wrapped with one column using group 2s
facet_wrap(~group2, ncol = 1, strip.position = "right", scales = "free_y") +
ylab("estimate")
figure.gg
Removing unused factors from grouped facet_grid bar plot
The problem is your use of scale_x_discrete
. You can transform response.cat
into an ordered factor instead:
plot.data$response.cat <- factor(plot.data$response.cat, levels = c("Strongly \ndisagree","Disagree","Mildly \ndisagree","Uncertain","Mildly \nagree","Agree","Strongly \nagree"))
ggplot(plot.data, aes(response.cat, score)) +
facet_grid(. ~ response.set, scales="free_x", space = "free_x") +
geom_bar(aes(fill = split), position = "dodge", stat="identity")+
scale_fill_manual(values=c(col.set), labels= plot.labels )+
ylim(c(0,100))+
theme(legend.title = element_blank(), legend.position = "bottom",
legend.text=element_text(colour= "gray23"), legend.key.height=unit(3,"mm")) +
theme(axis.title= element_blank()) +
geom_text(aes(fill = split, label = paste0(score,"%")), colour = "gray23", vjust=-1, position=position_dodge(.9),size=3)+
theme(panel.grid.minor.y = element_blank()) +
theme(panel.grid.major.y = element_line(colour = "gray")) +
theme(panel.grid.major.x =element_blank(), panel.grid.minor.x =element_blank()) +
theme(panel.background = element_rect(fill="white")) +
theme(axis.text.x = element_text(colour = "gray23")) +
theme(axis.text.y = element_text(colour = "gray23")) +
theme(axis.ticks.y=element_blank())
ggplot2: Drop unused factors in a faceted bar plot but not have differing bar widths between facets
How about this:
df$w <- 0.9
df$w[df$TIME == 5] <- 0.9 * 3/4
ggplot(df, aes(x=ID, y=VAL, fill=TYPE)) +
facet_wrap(~TIME, ncol=1, scale="free") +
geom_bar(position="stack",aes(width = w),stat = "identity") +
coord_flip()
Not sure if I got the arithmetic right there, but you get the idea.
Related Topics
Calculating Peaks in Histograms or Density Functions
Deleting Specific Rows from a Data Frame
How to Declare a Thousand Separator in Read.Csv
Rcpp Function to Select (And to Return) a Sub-Dataframe
Apply Function to Elements Over a List
Extract Digit from Numeric in R
Find Matching Strings Between Two Vectors in R
How Does R Handle Unicode/Utf-8
R Grep Pattern Regex with Brackets
Overlay Grid Rather Than Draw on Top of It
New R-Studio Version 0.98.932 Deletes .Md File - How to Prevent
Error in File(File, "Rt"):Invalid 'Description' Argument in Complete.Cases Program
Any Way to Force Fread() of Data.Table Not to Stop on Empty Lines
In R, How to Check If Two Variable Names Reference the Same Underlying Object
Assigning by Reference into Loaded Package Datasets
Coloring Boxplot Outlier Points in Ggplot2
How to Add Shaded Confidence Intervals to Line Plot with Specified Values