Let's Yo
Let's Yo

Reputation: 333

Plotting chart with table dataframe

Is there anyway to plot the table in a horizontal way not in vertical way? and to plot the table without the labels?

the code I have:

Product <- c("Product1","Product2","Product3","Product4","Product5","Product6","Product7")
Value <- c(1000000,200002,599996,1399994,2199992,2999990,3799988)
df <- data.frame(Product,Value)
df$Product <- factor(df$Product, 
                     ordered = TRUE, 
                     levels = c("Product7","Product6","Product5","Product4","Product3",
                                "Product2","Product1"))

library(ggplot2)

p <- ggplot(df,aes(x=1,y=Value,fill=Product))+geom_bar(stat="identity")
p <- p + coord_polar(theta='y')+ 
  theme(axis.ticks=element_blank(),
        axis.text.y=element_blank(),
        axis.text.x=element_text(colour='black', size=12),
        axis.title=element_blank())
p <- p + scale_y_continuous(breaks=cumsum(df$Value) - df$Value / 2, 
                            labels= (paste(Product, 
                                           paste(round(((df$Value/sum(df$Value))*100),2),
                                                 "%"), 
                                           sep="\n")))
p <- p + guides(fill=FALSE)
p <- p + theme(panel.background = element_blank())

library(gridExtra)

t <- tableGrob(df)
grid.arrange(p,t)

enter image description here

I want it be like this

enter image description here

Upvotes: 0

Views: 347

Answers (1)

Z.Lin
Z.Lin

Reputation: 29085

You can replace tableGrob(df) in the second last line with tableGrob(t(df)) to transpose the dataframe before passing it to tableGrob().

If you prefer a cleaner look without the grey background in each cell, use:

tableGrob(t(df), theme = ttheme_minimal())

I would also suggest not naming it t, as it is the name of a base package function.

Lastly, if you want to allocate more space to the pie chart, you can assign a height ratio of something other than c(1, 1):

tt <- tableGrob(t(df), theme = ttheme_minimal())
grid.arrange(p, tt, heights = c(4, 1))

plot

Side note: The code for p can also be simplified to the following:

ggplot(df, aes(x = 1, y = Value, fill = Product,
               label = paste(Product, "\n",
                             scales::percent(Value / sum(Value))))) + 
  geom_col() + 
  geom_text(aes(x = 1.6), # change this to shift label. smaller x = closer to pie center
            position = position_stack(vjust = 0.5)) +
  coord_polar(theta = 'y') +
  theme_void() +
  guides(fill = FALSE)

Explanation:

  • geom_col() is equivalent to geom_bar(stat = "identity");
  • setting pie slice labels in aes() & adding a geom_text() layer is generally cleaner than customizing breaks along the y-axis;
  • use percent() from scales package instead of manually converting a decimal value to percent format;
  • theme_void() removes all axis ticks, text, title, background, etc., in one line.

Upvotes: 2

Related Questions