Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adjustment of geom_area #6153

Closed
Breeze-Hu opened this issue Oct 22, 2024 · 2 comments
Closed

Adjustment of geom_area #6153

Breeze-Hu opened this issue Oct 22, 2024 · 2 comments

Comments

@Breeze-Hu
Copy link

ggplot2 has a very elegant way of plotting graphs, especially statistical graphs. However, I have encountered some difficulties in adjusting the area graph.

I want to plot areas of two colors, red for parts greater than 0, and blue for parts less than 0. After trying a few approaches (see code below), it was possible to approximate the desired result in a large dataset, but there were still some problems.
Is there a suggestion or a better way to present this part of the code?

Some some representations of matplotlib would be more concise and predictable, so I hope there is some reference:
[matplotlib](https://matplotlib.org/stable/gallery/lines_bars_and_markers/fill_betweenx_demo.html
https://matplotlib.org/stable/gallery/lines_bars_and_markers/fill_between_demo.html (interpolate parameter))

test = tibble(x=1:5,
              y = c(-1,1,3,-4,2)) |> 
  mutate(y_na = ifelse(y<0, y, 0), y_po = ifelse(y>0, y, 0))

ggplot(test)+
  geom_area(aes(x = x, y = y_po),fill='red')+
  geom_area(aes(x = x, y = y_na),fill='blue')

image

@teunbrand
Copy link
Collaborator

There are already extensions doing what you indicate:

library(ggplot2)

test <- data.frame(x = 1:5, y = c(-1, 1, 3, -4, 2))

ggplot(test, aes(x, ymax = y, ymin = 0)) +
  ggh4x::stat_difference()

ggplot(test, aes(x, ymax = y, ymin = 0, fill = y < 0)) +
  ggbraid::geom_braid(method = "line")

Created on 2024-10-22 with reprex v2.1.1

@Breeze-Hu
Copy link
Author

Thank you! this is exactly the result I was looking for!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants