0
votes

I have a dataframe as shown below, in which i would like to plot "FREQ" values on X-axis as a line graph for each class in TYPE with the total count on Y-axis

ID     FREQ    TYPE
ID1    0.0827068    A
ID2    0.0827068    A
ID3    0.0150376    B
ID4    0.0075188    B
ID5    0.07838      C
ID6    0.0676692    C

I managed to plot a histogram with the below command:

ggplot(CNV.sort1, aes(x = FREQ,y=..density..,fill=TYPE)) + geom_histogram()

geom_line

However, i would need a line graph with the X-axis breaks as shown below and total events at each data point on Y-axis.

enter image description here

I tried using geom_line()

ggplot(CNV.sort1, aes(x = FREQ,y=..density..,fill=TYPE)) + geom_line()
Error in eval(expr, envir, enclos) : object 'density' not found

I am missing out something to get a line graph. Any clues offered will be helpful!!

1

1 Answers

0
votes

It can be solved the hard way:

You can use base function hist() and enter its slots:

h <- hist(rnorm(1000,1,10)) 

Histogram may have precised breaks xlim and so on, so they would satisfy you. Then you can use str() to see its slots and access them.

Slot h$breaks is longer than slots h$counts and h$density that are of your interest, so you need to manually adjust them.

When you get the right vectors, you can plot them with line methods. It may be ggplot or base:

plot(vector1, vector2, type = "l")

As i said, this is quite a hard way. It would be much better to have one function for that, but in case no better answer is provided - this may work. Also feel free to ask if you need step by step guide.

EDIT:

Here is the code doing what is described above:

# creating sample data frame:
ID <- paste0("ID", 1:1000)
FREQ <- rnorm(1000, 0.5, 0.1)
TYPE <- sample(c("A", "B", "C"), size = 1000, replace = T)
d <- data.frame(ID, FREQ, TYPE)
head(d)

# creating histogram and entering slots:
h <- hist(d$FREQ[d$TYPE == "A"])
str(h)

# geting and adjusting needed vectors:
counts = h$counts
values = h$breaks[2:length(h$breaks)] - 0.5 * (h$breaks[2] - h$breaks[1])

# plotting histogram with line:
plot(values, counts, type = "l")