0

My code with the following output (below in the picture) calculates the average price of the neighbourhood groups. Beside the mean I also want to add the median price label. How should I add this information to the graph?

{r }
p.nbr <- ny_explor %>%
  group_by(neighbourhood_group) %>%
  summarise(price = round(mean(price), 2))

ggplot(ny_explor, aes(price)) +
  geom_histogram(bins = 30, aes(y = ..density..), fill = "darkslategrey") + 
  geom_density(alpha = 0.2, fill = "darkslategrey") +
  theme_bw() +
  ggtitle("Distribution of price by neighbourhood groups",
          subtitle = expression("With" ~'log'[10] ~ "transformation of x-axis")) +
  geom_vline(data = p.nbr, aes(xintercept = price), size = 2, linetype = 3) +
  geom_text(data = p.nbr,y = 1.5, aes(x = price + 1400, label = paste("Mean  = ",price)), color = "saddlebrown", size = 4) +
  facet_wrap(~neighbourhood_group) +
  scale_x_log10()

enter image description here

L.Lauenburg
  • 462
  • 5
  • 19
  • It's easier to help you if you include a simple [reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) with sample input and desired output that can be used to test and verify possible solutions. – MrFlick Dec 11 '20 at 16:10
  • 1
    In your summarize make a column for both the mean and median price, then use `pivot_longer` to pivot those two columns making one column a descriptor variable (mean or median) and the another column the actual values. Then you can use the descriptor column to distinguish mean vs median in your `geom_text` – cookesd Dec 11 '20 at 17:48

1 Answers1

0

Though it would have been easier if you could include some sample data, yet it is advised that your existing code may be modified like this, which may work. If not, please incluide some sample data

p.nbr <- ny_explor %>%
  group_by(neighbourhood_group) %>%
  summarise(price_mean = round(mean(price), 2),
            price_median = median(price))

ggplot(ny_explor, aes(price_mean)) +
  geom_histogram(bins = 30, aes(y = ..density..), fill = "darkslategrey") + 
  geom_density(alpha = 0.2, fill = "darkslategrey") +
  theme_bw() +
  ggtitle("Distribution of price by neighbourhood groups",
          subtitle = expression("With" ~'log'[10] ~ "transformation of x-axis")) +
  geom_vline(data = p.nbr, aes(xintercept = price_mean), size = 2, linetype = 3) +
  geom_text(data = p.nbr,y = 1.5, aes(x = price_mean + 1400, label = paste("Mean  = ",price_mean), 
                                                                      "/nMedian = ", price_median), color = "saddlebrown", size = 4) +
  facet_wrap(~neighbourhood_group) +
  scale_x_log10()

AnilGoyal
  • 25,297
  • 4
  • 27
  • 45