R语言ggplot中scale_y_log10下设置y轴极值(含0)的方法求助
Hey there! I get why you're frustrated—trying to set a log scale y-axis that includes 0 can feel counterintuitive at first, since log₁₀(0) is mathematically undefined (it's negative infinity). That's exactly why your limits = c(?, ?) parameter wasn't working with scale_y_log10()—ggplot can't handle 0 in a pure log scale.
Here are two solid solutions tailored to your voltage drop plot:
Option 1: Use a Pseudologarithmic Transform (Best for Data Near 0)
Pseudolog scales act linearly near 0 and switch to logarithmic scaling for larger values, which is perfect for your voltage decay data (where voltage approaches 0 over time). This lets you formally include 0 in your axis limits without mathematical issues.
Modify your code like this:
ggplot(data = rc_data, aes(x = t, y = Vc))+ geom_point()+ geom_smooth(method = lm, se = FALSE) + labs(x = "Time (sec)", y = "Voltage (V), Pseudolog Scale") + ggtitle("Drop of Voltage of a ...") + scale_y_continuous( trans = "pseudolog10", # Enables 0-compatible log-like scaling limits = c(0, max(rc_data$Vc)), # Explicitly set 0 as the minimum breaks = c(0, 1, 10, 100) # Adjust these to match your data's range )
Option 2: Fake 0 on a Pure Log Scale (If You Need Strict Log Scaling)
If you absolutely must use a pure log₁₀ scale, you can trick ggplot into displaying 0 by using a tiny positive value as the actual limit, then relabeling it as 0. This works visually, even though the underlying scale doesn't include 0 mathematically.
Try this code:
ggplot(data = rc_data, aes(x = t, y = Vc))+ geom_point()+ geom_smooth(method = lm, se = FALSE) + labs(x = "Time (sec)", y = "Voltage (V), Log Scale") + ggtitle("Drop of Voltage of a ...") + scale_y_log10( limits = c(1e-6, max(rc_data$Vc)), # Use a tiny positive value as the lower limit expand = expansion(mult = c(0.1, 0.1)), # Extend axis to visually reach 0 breaks = c(1e-6, 1e-3, 1, 10, 100), # Include the tiny value in breaks labels = c("0", "0.001", "1", "10", "100") # Relabel the tiny value as 0 )
Quick Note on Why Your Original Code Failed
scale_y_log10() automatically ignores any limit that includes 0 (or negative numbers) because logarithmic transformations can't process non-positive values. The solutions above work around this either by using a transform that handles 0, or by visually mimicking 0 on a valid log scale.
内容的提问来源于stack exchange,提问作者SomebodyNeedingHelp

