问题
I am trying to create a bar graph. When I set the limits as (0,7), the bars appear. However, I would like the lower limit to be 1, not 0. When I set the lower limit to 1, the bars do not appear. I get the following error message:
Removed 8 rows containing missing values (geom_bar).
It doesn't matter how I set the limits. I have used both of the following options:
ylim(1, 7)
scale_y_continuous(limits = c(1, 7))
Does anyone know how I can fix this?
I'd like a graph that looks like this, but with 1 as the lower y-axis label, which would mean all the bars would be shifted down by 1.
Here's the full code for the graph:
full %>%
ggplot(aes(x = order, y = mean)) +
geom_bar(stat = "identity", fill = "003900", width = 0.5, position = position_dodge()) +
geom_errorbar(aes(ymin = mean - se, ymax = mean + se), width = .2, position = position_dodge(.9)) +
geom_text(aes(label = round(mean, digits =1)), position = position_dodge(width=1.0), vjust = -4.0, size = 3) +
#facet_wrap(~names) +
labs(title = "Behavioral intentions in response to each message") +
# ylim(0, 7) +
scale_y_continuous(limits = c(1, 7)) +
theme(axis.text = element_text(size = 7)) +
xlab("Message") +
ylab("Behavioral intentions")
Here's reproducible data:
structure(list(message = c("a", "e", "h", "m", "convince_animals",
"convince_environment", "convince_health", "convince_money"),
mean = c(3.1038961038961, 3.21052631578947, 3.56, 2.7972972972973,
4.19512195121951, 4.18536585365854, 5.65365853658537, 4.93658536585366
), se = c(0.208814981196227, 0.204609846510406, 0.220760356801522,
0.20542415978608, 0.121188432228325, 0.11075110910238, 0.0896896391724367,
0.120394657272105), type = c("Behavioral Intentions", "Behavioral Intentions",
"Behavioral Intentions", "Behavioral Intentions", "Expected Behavior",
"Expected Behavior", "Expected Behavior", "Expected Behavior"
), names = c("Animals", "Environment", "Health", "Money",
"Animals", "Environment", "Health", "Money"), order = c(1,
3, 5, 7, 2, 4, 6, 8)), row.names = c(NA, -8L), class = c("tbl_df",
"tbl", "data.frame"))
回答1:
Looks like you're losing data by setting limits and it's screwing up your plot. You can use coord_cartesian()
instead of ylim()
to 'zoom in' on your data; see https://stackoverflow.com/a/25685952/12957340 and/or page 160 of the ggplot2 book for further info.
full %>%
ggplot(aes(x = order, y = mean)) +
geom_bar(stat = "identity", fill = "003900", width = 0.5, position = position_dodge()) +
geom_errorbar(aes(ymin = mean - se, ymax = mean + se), width = .2, position = position_dodge(.9)) +
geom_text(aes(label = round(mean, digits =1)), position = position_dodge(width=1.0), vjust = -4.0, size = 3) +
#facet_wrap(~names) +
labs(title = "Behavioral intentions in response to each message") +
coord_cartesian(ylim = c(1, 7)) +
theme(axis.text = element_text(size = 7)) +
xlab("Message") +
ylab("Behavioral intentions")
来源:https://stackoverflow.com/questions/66020146/graph-bars-only-appear-when-lower-limit-of-y-axis-set-to-0-in-ggplot