Shiny环境中ggplotly绘图的4项优化需求咨询
Solution to Your ggplot/Plotly Customization Questions
Hey there! Let's work through each of your four customization needs step by step, then put it all together in the updated code.
Key Modifications Explained
- 1. Legend placement & horizontal layout: We'll set
legend.position = "top"and addlegend.direction = "horizontal"in thetheme()layer, plus adjust margins to prevent overlap between the title and legend. - 2. Bold, centered title: Use
element_text(face = "bold", hjust = 0.5)intheme(plot.title = ...)to style the title exactly as you want. - 3. Point shapes by Disability: Move
shape = Disabilityinto theaes()ofgeom_point()so shapes are mapped to the Disability variable. You can optionally usescale_shape_manual()to set custom shapes if you prefer specific ones. - 4. Rename y-axis label: Ensure the
labs()layer explicitly setsy = "Age at Death"to replace the defaultAgeatDeathlabel pulled from your data.
Updated Full Code
# Assuming blue.bold.10.text is already defined in your environment blue.bold.10.text <- element_text(color = "blue", face = "bold", size = 10) IDD_line <- ggplot(IDD_plot) + geom_line(aes(x = Year, y = AgeatDeath, color = Disability), size = 1) + # Map shape to Disability variable in geom_point's aesthetic geom_point(aes(x = Year, y = AgeatDeath, color = Disability, shape = Disability), size = 1.5) + scale_x_continuous(breaks = seq(2008, 2017, 1)) + # Set y-axis label to "Age at Death" labs( x = "Year", y = "Age at Death", caption = "" ) + theme_bw() + scale_y_continuous(breaks = seq(35, 80, 5)) + ggtitle("Age of Death by Year (2008 to 2017)") + theme( legend.title = element_blank(), axis.text = blue.bold.10.text, # Position legend at top with horizontal layout legend.position = "top", legend.direction = "horizontal", # Style title: bold + centered, add bottom margin for spacing plot.title = element_text(face = "bold", hjust = 0.5, margin = margin(b = 10)), # Adjust plot margins to prevent crowding plot.margin = margin(t = 10, r = 10, b = 10, l = 10) ) + # Optional: Customize shapes for each Disability category (adjust values to match your category count) scale_shape_manual(values = c(21, 22, 23)) output$IDD_plot <- renderPlotly(ggplotly(IDD_line) %>% config(displayModeBar = F))
Quick Notes
- If your
Disabilityvariable has more than 3 categories, update thevaluesinscale_shape_manual()to include enough unique shapes (ggplot has 25 built-in shapes to choose from). - Tweak the margin values if you need more/less spacing between the title, legend, and plot area for your specific output size.
内容的提问来源于stack exchange,提问作者Nader Mehri
相关产品推荐
相关产品推荐

