R: Align table with the graphs by y-axis

90 views Asked by At

I have two charts and 1 table generated. What I want is to have all of them put in 1 row and aligned so each row within the table is on the same level as graph, so it looks like one swimlane.

I am trying to align all those using ggarrange, trying to specify axis as tb/y etc.

combined_plot <- ggarrange(
  table_grob, average_chart, percentile_chart,
  ncol = 3, nrow = 1, align = "h", axis = "y")

but it fails anyway with:

Warning messages:
1: Graphs cannot be horizontally aligned unless the axis parameter is set. Placing graphs unaligned. 
2: In as_grob.default(plot) :
  Cannot convert object of class character into a grob.

So I ended up with grid.arrage, however using in straightforward does a poor job which needs to be adjusted further: r-graph

Any ideas how to make that gracefully? Googled a bit, but I didn't find great solution yet.

My initial code is:

combinded_plot <- grid.arrange(
  table_grob,
  percentile_chart,
  average_chart,
  ncol = 3,
  widths = c(1, 1, 1),
  heights = c(0.2, 0.4, 0.4),
  clip = FALSE
)

My full code is:

# Load required libraries
library(ggplot2)
library(dplyr)
library(tidyr)
library(gridExtra)
library(patchwork)

# Sample data (replace with your actual data)
data <- data.frame(
  label = c("Label A", "Label B", "Label A", "Label B"),
  Latency = c(100, 150, 200, 250)
)

# Calculate average and 95th percentile for each label
summary_data <- data %>%
  group_by(label) %>%
  summarize(Average = mean(Latency), Percentile95 = quantile(Latency, 0.95))

# Find the maximum average for setting the x-axis limit
max_average <- max(summary_data$Average)
x_limit <- 1.5 * max_average

# Create the bar chart for average latency
average_chart <- ggplot(summary_data, aes(y = label, x = Average)) +
  geom_bar(stat = "identity", fill = "blue") +
  geom_text(aes(label = round(Average, 2)), hjust = -0.2) +
  xlim(0, x_limit) +
  labs(x = "Average Latency", y = "Label") +
  ggtitle("Average Latency by Label")

# Create the bar chart for the 95th percentile
percentile_chart <- ggplot(summary_data, aes(y = label, x = Percentile95)) +
  geom_bar(stat = "identity", fill = "green") +
  geom_text(aes(label = round(Percentile95, 2)), hjust = -0.2) +
  xlim(0, x_limit) +
  labs(x = "95th Percentile", y = "") +
  ggtitle("95th Percentile Latency by Label")

label_table <- data %>%
  group_by(label) %>%
  summarise(MeasurementCount = n())

table_grob <- tableGrob(label_table)

combinded_plot <- grid.arrange(
  table_grob,
  percentile_chart,
  average_chart,
  ncol = 3,
  widths = c(1, 1, 1),
  heights = c(0.2, 0.4, 0.4),
  clip = FALSE
)
# Print or display the combined plot
print(combined_plot)```

Related to:
https://stackoverflow.com/questions/54312894/how-to-align-table-and-plot-in-rmarkdown-html-document
https://stackoverflow.com/questions/73250489/how-to-align-table-with-forest-plot-ggplot2
0

There are 0 answers