Based on the data and code, when I define the ylim
, I get an empty plot.
How can I fix this? The purpose is to make the y-axis scale more relative to the y-axis values.
Sample Data (df
):
df = structure(list(CITYNAME = c("A", "B", "C",
"D", "E", "F", "G",
"H", "I", "J", "K",
"L", "M", "N", "O", "P",
"Q", "R", "S", "T",
"U", "V", "W", "X"), AvgTMin = c(20.2816084328988,
20.3840825075794, 20.0835783555714, 20.347418425369, 20.3811359868631,
20.7554449391855, 20.9974032162639, 21.2099738161653, 20.4519932648135,
20.2125743740635, 21.1833765506329, 20.2896719963552, 20.6081700987288,
20.435186095623, 20.9495391505466, 19.7528992240298, 20.5827896792107,
20.3185165984173, 21.0522389837351, 20.2764728930218, 20.0887610057421,
20.1485958052192, 20.7300726136944, 20.1160170580025)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -24L))
Code:
library(tidyverse)
df %>%
ggplot(aes(x = reorder(CITYNAME,AvgTMin), y = AvgTMin, fill = CITYNAME))
geom_bar(stat="identity")
ylim(15,23) #ylim causing an empty plot
labs(fill = "Legend", x = NULL, y = "Avg. Min. Tempreture \u00B0C")
theme(axis.text.x = element_text(angle = 90))
ggtitle("Temperature Trend By City")
CodePudding user response:
You should use coord_cartesian
with ylim
like this:
df = structure(list(CITYNAME = c("A", "B", "C",
"D", "E", "F", "G",
"H", "I", "J", "K",
"L", "M", "N", "O", "P",
"Q", "R", "S", "T",
"U", "V", "W", "X"), AvgTMin = c(20.2816084328988,
20.3840825075794, 20.0835783555714, 20.347418425369, 20.3811359868631,
20.7554449391855, 20.9974032162639, 21.2099738161653, 20.4519932648135,
20.2125743740635, 21.1833765506329, 20.2896719963552, 20.6081700987288,
20.435186095623, 20.9495391505466, 19.7528992240298, 20.5827896792107,
20.3185165984173, 21.0522389837351, 20.2764728930218, 20.0887610057421,
20.1485958052192, 20.7300726136944, 20.1160170580025)), class = c("tbl_df",
"tbl", "data.frame"), row.names = c(NA, -24L))
library(tidyverse)
df %>%
ggplot(aes(x = reorder(CITYNAME,AvgTMin), y = AvgTMin, fill = CITYNAME))
geom_bar(stat="identity")
labs(fill = "Legend", x = NULL, y = "Avg. Min. Tempreture \u00B0C")
theme(axis.text.x = element_text(angle = 90))
ggtitle("Temperature Trend By City")
coord_cartesian(ylim = c(15,23))
Created on 2022-07-22 by the reprex package (v2.0.1)