0

I made this .csv file called pie_chart.csv. I've been trying to make a pie chart for every single sample that is on there, with the other columns being categories that the pie charts display. I currently have this so far:

#Pie Chart
library(readr)
x <- read_csv("pie_chart.csv")

#rename the first column
colnames(x)[colnames(x)=="X1"] <- "Sample"

I am confused as to how to continue from here. I have tried a for loop but would appreciate any help that is given! Thank you!

I transposed the data and tried using a for loop. In another data set this worked, however, for this data it is giving me errors:

x <- t(x)
names2 <- colnames(x[,2])[colnames(x) != "Sample"]
for (i in 2:col) { 
  mypath2 <- file.path("C:","Users", "Prak Lab", "Desktop","REPORTS", "text files", 
                       paste(names2[i],"pie", ".jpg", sep = ""))
  jpeg(file = mypath2)
  pie(table(x[,i]), labels = x[,1], col = c("darkred","pink"), main = colnames(x[i]))
  #title = colnames(x[i])
  dev.off()  
}

This is head(x):

  Sample           Reads_used_in_Clonotypes   Unsuccessful_Reads   Not_used_for_Clonotypes
1 012-915-8-rep1                      0.772               0.1540                    0.0743
2 012-915-8-rep2                      0.888               0.0436                    0.0681
3 012-915-8-rep3                      0.856               0.0470                    0.0966
4 012-915-8-rep4                      0.873               0.0525                    0.0741
5 012-915-8-rep5                      0.860               0.0440                    0.0962
6 012-915-8-rep6                      0.905               0.0286                    0.0667
r2evans
  • 141,215
  • 6
  • 77
  • 149
Lasarus9
  • 83
  • 9
  • 1
    Welcome to Stack Overflow! The assumption here is that you've looked for how to solve your question and have gotten stuck. Have you tried googling "r pie chart"? These links seem pretty apropos: https://www.statmethods.net/graphs/pie.html https://www.tutorialspoint.com/r/r_pie_charts.htm http://www.sthda.com/english/wiki/ggplot2-pie-chart-quick-start-guide-r-software-and-data-visualization – Jon Spring Oct 29 '18 at 20:34
  • Once you've gone through links like JonSpring suggested, if you still have questions about code you've tried that does not work, I think your question will need to be edited a little. You've included some code which is good, please update with any pie-chart-related code you're able to derive, but also include *representative data*. This can be something constructed (e.g., `data.frame(...)`) or a sample of your actual data (`dput(head(x))`), assuming that this sample contains enough of a couple of groups to prove your point. Ref: https://stackoverflow.com/questions/5963269 – r2evans Oct 29 '18 at 20:40
  • I added more code. I keep getting this: Error in 2:col : NA/NaN argument – Lasarus9 Oct 29 '18 at 20:53
  • Links to externally-stored data are generally discouraged on SO: when the link goes dead (not "if"), the question becomes unreproducible. Unless I'm missing something, you could easily include the output from `dput(head(x))` and lose no context in your question. – r2evans Oct 29 '18 at 20:56

2 Answers2

0

I suppose you mean something like this:

enter image description here

Here's the code to generate the plot. I load several packages such as ggplot2, reshape, and dplyr since they make things more convenient.

# Your code (slightly modified, using read.csv instead)
x <- read.csv("pie_chart.csv")
colnames(x)[colnames(x)=="X"] <- "Sample"

# My code starts here:
library(ggplot2)
library(reshape)
library(dplyr)

# Rearrange the data to make it easier for plotting
x2 <- melt(x, id.vars = "Sample") %>% arrange(Sample, variable)

# Open an empty png file; alternatively you can use pdf("Sample.pdf",....)
png("Sample.png", width = 1600, height = 1600)
# Plot the graph. I changed the theme a little bit but feel free to change any of it
ggplot(x2, aes(x= "", y = value, fill = variable))+ geom_bar(width = 1, stat = "identity") + 
  coord_polar("y", start=0) + 
  theme(axis.text.x=element_blank(),
        axis.title.x = element_blank(),
        axis.title.y = element_blank(),
        panel.border = element_blank(),
        panel.grid=element_blank(),
        axis.ticks = element_blank(),
  ) +
  facet_wrap(~Sample)
# Save the png file
dev.off()

Good luck! Let me know if you have any other questions. For pie charts with ggplot2, I found this link pretty useful.

Jiafei Li
  • 53
  • 7
  • 1
    Thank you so much! I'm literally going line by line to understand this, and thank you for the link! – Lasarus9 Oct 29 '18 at 21:09
  • I'm glad to hear that! Best of luck for your research! – Jiafei Li Oct 29 '18 at 21:17
  • If i want to manually change the colors, should i add `scale_fill_manual()` ? Also, does the placement matter? Does it have to be before `theme()`? Thank you so much btw! This really helped! – Lasarus9 Dec 05 '18 at 16:27
0

First: when you transpose the data with t(x), you are converting everything to character. This is because t returns a matrix, not a data.frame. Everything in a matrix must be of the same class, so a common-class is found and conversions are done: character > numeric > integer > logical (or less-than, your choice), where if there is one character (or factor) column, then everything is converted.

If you truly want one image for each row, then something like this might work.

First, some data:

x <- read.csv(header=TRUE, check.names=FALSE, text = "
,Reads used in Clonotypes,Unsuccessful Reads,Not used for Clonotypes
012-915-8-rep1,0.772143599,0.153575355,0.074281045
012-915-8-rep2,0.888258155,0.043600206,0.068141639
012-915-8-rep3,0.856428962,0.046993738,0.0965773
012-915-8-rep4,0.873364731,0.05249563,0.074139639")
colnames(x)[1] <- "Sample"

And the loop. I've commented out the jpeg/dev.off code for local demonstration. I also added a color (NA for no color), since I'm inferring you wanted all three columns shown in the pie chart. Adjust if I'm incorrect.

for (i in seq_len(nrow(x))) {
  fn <- paste0(x$Sample[i], ".jpg")
  # jpeg(file = fn)
  pie(unlist(x[i,-1]), col = c(NA, "darkred", "pink"),
      main = x$Sample[i])
  legend("bottomleft", sprintf("%0.1f%% - %s", 100*x[i,-1], names(x[i,-1])), bty='n')
  # dev.off()
}

The first chart is:

first pie chart

You will likely notice that your labels will go off the page if the aspect ratio and radius= (argument for pie) are not managed well, play with it.

The legend is harder to keep within the bounds ... as the overlap with the pie chart itself demonstrates.

Lastly, I'll quote from the help documentation of this function (?pie), a reason I was somewhat hesitant to provide this answer in the first place:

 Pie charts are a very bad way of displaying information.  The eye
 is good at judging linear measures and bad at judging relative
 areas.  A bar chart or dot chart is a preferable way of displaying
 this type of data.

 Cleveland (1985), page 264: "Data that can be shown by pie charts
 always can be shown by a dot chart.  This means that judgements of
 position along a common scale can be made instead of the less
 accurate angle judgements."  This statement is based on the
 empirical investigations of Cleveland and McGill as well as
 investigations by perceptual psychologists.
r2evans
  • 141,215
  • 6
  • 77
  • 149
  • If that meets your needs, please "accept" the more appropriate of the two answers. – r2evans Oct 29 '18 at 21:22
  • I am currently trying to add percentages and a legend, and I think I have piepercent all wrong, and I believe that it is the line that is giving me errors. `for (i in seq_len(nrow(x))) { fn <- paste0(x$Sample[i], ".jpg") jpeg(file = fn) piepercent <-(100*x) pie(unlist(x[i,-1]), labels = piepercent, col = c("blue", "darkred", "pink"), main = x$Sample[i]) legend("topright", c("Reads Used in Clonotypes", "Unsuccessful Read", "Not Used"), cex = 0.8, fill = rainbow(length(x))) dev.off() }` I want to have the percents be the labels on the chart. – Lasarus9 Oct 30 '18 at 13:53
  • Isn't `(100*x)` multiplying 100 by the entire frame `x`?? That makes no sense, why wouldn't you use the same numeric component being fed to `pie`, ala `unlist(x[i,-1])`? – r2evans Oct 30 '18 at 14:31