简体   繁体   中英

Pie Chart R programming

Create a pie chart for the top 6 entries of the mtcars dataset. Plot the mpg values against the row names(labels) of the dataset. I tried with this code but may be I am not able to understand the question correctly as in katacoda environment I am not able to move forward.
Code:

count = table(mtcars$mpg[1:6])
pie(count)

在此处输入图像描述

This has nothing to do with table , which would count the number of equal values, the variable mpg is continuous.
The question asks to plot the top 6 values of mpg against row.names(mtcars) .

x <- setNames(mtcars$mpg[1:6], row.names(mtcars)[1:6])
pie(x)

在此处输入图像描述

Maybe highcharter?

highchart() %>% 
hc_add_series(data=cbind(name=rownames(mtcars),mtcars)[1:6,],
type="pie",hcaes(name=name,y=mpg))

在此处输入图像描述

Slightly odd plot (I'm not sure I fully understand what you're going for), but you should be able to adapt this

library(ggplot2)
library(ggforce)

mtcars_sub <- head(mtcars, 6)
mtcars_sub$names <- rownames(mtcars_sub)

ggplot(mtcars_sub) +
  geom_arc_bar(aes(x0 = 0, y0 = 0, r0 = 0, r = 1, amount = mpg, fill = names), stat = "pie")

Although I far prefer this as a bar chart. I think its much more interpretable

ggplot(mtcars_sub) +
  geom_col(aes(y = mpg, x = names, fill = names))

Try these set of commands

data(mtcars)
pie(table(mtcars$mpg[1:6]),labels=row.names(mtcars)[1:6])
data(mtcars)
count <- table(mtcars$mpg[1:6])
pie(count, labels = row.names(mtcars)[1:6])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM