Quantcast
Channel: Recent Questions - Stack Overflow
Viewing all articles
Browse latest Browse all 12141

Adding equidistant x scale and a legend for each line of a ggplot using R

$
0
0

enter image description hereFor this graph, I want to make it look like the graph in the first picture basically. The problem I am having with reproducing this graph is that I can't get the scale to look like it. The goal is to have the scale have the values in the vector "powers" equidistant to each other. I did manage to do so with the help of ChatGPT, but although the scale is correct, the points on the graph are no longer aligned to the according points on the scale. Another goal for me is to have a legend like the one in the first graph, but I'm not sure how to make it. Would the for loop affect having the legend indicate each line?

powers <- c(0,0.25,0.33,0.35,0.375,0.4,0.425,0.45,0.475,0.5,0.525,0.55,0.575,            0.6,0.7,0.8,0.9,1,1.1,1.2,1.3)density_vs_power <- ggplot(data = as.data.frame(graph_data))colors <- rainbow(21)# Loop to add geom_line layers for each columnfor (i in 4:24) {  density_vs_power <- density_vs_power + geom_line(aes(x = powers, y = !!sym(as.character(i))), color = i) +    geom_point(shape = i, aes(x = powers, y = !!sym(as.character(i))), color = i)}equidistant_breaks <- seq(min(powers), max(powers), length.out = length(powers))# Add scale and themedensity_vs_power <- density_vs_power +  scale_y_continuous(trans = "log10") +  theme_classic() +  scale_x_continuous(trans = "log10") +scale_x_continuous(breaks = equidistant_breaks, labels = powers)

Sadly, graph_data is too large a data frame to be presented here.

Using the method GPT gave, I created the equidistant_breaks sequence to make the scale equidistant. However, I just found out that I need to add "period" into my "powers" vector, so the x scale has to be discrete. This feels like more of a box plot, for which the x are discrete names and the y are the according values. However, I do need the plot to be lines, so I think the right approach here is with an discrete x scale? I tried with something like scale_x_discrete(breaks = powers, labels = powers) , but it doesn't work and even stops showing the x axis labels.

For the legends part, I simply have no idea how to do it, and GPT does not give helpful solutions. Since the points and lines are technically separated, how can I still make them appear as one thing on the legend?

As an absolute beginner, any help is much appreciated!


Viewing all articles
Browse latest Browse all 12141

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>