J. D. Vidal
J. D. Vidal

Reputation: 21

geom_bar messing with y_axis scale

I have some elevation data which I would like to associate with climatic categories in a dataset. When I try to plot it as a barplot to see the distribution of the categories along the elevation, something in ggplot's geom_bar converts the y axis scale to some weird values. Here is the example:

# Example dataset
data_mountain_A <- data.frame(elevation=c(0,500,1000,1500,2000),
                              temperature=c(20,16,12,8,5),
                              name="A")
data_mountain_B <- data.frame(elevation=c(0,500,1000,1500,2000,2500,3000),
                              temperature=c(20,16,12,8,5,0,-5),
                              name="B")
data_merge <- rbind(data_mountain_A, data_mountain_B)

# Creates the temperature intervals
data_merge$temperature_intervals <- cut(data_merge$temperature,seq(-5,20,5))

# Fancy colors
colfunc <- colorRampPalette(c("white","light blue","dark green"))

# Plot
ggplot(data=data_merge, aes(fill=temperature_intervals, y=elevation, x=name)) + 
  geom_bar(stat="identity") +
  scale_fill_manual(values=colfunc(5))

And here is the output I get:

Any hints on what am I doing wrong? Thanks!

EDIT: I've found out the issue. It was considering the elevation as a range, not as a single measure. I fixed it by replacing the elevation absolute values by the length of the elevation intervals.

Upvotes: 0

Views: 263

Answers (1)

J. D. Vidal
J. D. Vidal

Reputation: 21

I've found out the issue. It was considering the elevation as a range, not as a single measure. I fixed it by replacing the elevation absolute values by the length of the elevation intervals.

# Example dataset
data_mountain_A <- data.frame(elevation=c(500,500,500,500,500),
                              temperature=c(20,16,12,8,5),
                              name="A")
data_mountain_B <- data.frame(elevation=c(500,500,500,500,500,500,500),
                              temperature=c(20,16,12,8,5,0,-5),
                              name="B")
data_merge <- rbind(data_mountain_A, data_mountain_B)

# Creates the temperature intervals
data_merge$temperature_intervals <- cut(data_merge$temperature,seq(-5,20,5))

# Fancy colors
colfunc <- colorRampPalette(c("white","light blue","dark green"))

# Plot
ggplot(data=data_merge, aes(fill=temperature_intervals, y=elevation, x=name))+geom_bar(position="stack",stat="identity")+
  scale_fill_manual(values=colfunc(5))

Upvotes: 1

Related Questions