You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在马赛克图中为不同有序类别上色?含三类特定类别配色需求及代码

Hey there! Customizing the colors for specific categories in your mosaic plot is straightforward with R's mosaicplot() function. Let's break down how to make "Not rude", "Somewhat rude", and "Very rude" each have their own distinct color.

Step-by-Step Solution

First, let's confirm your data and original code for context:

Your Data Table:

table2p
rbabyF hchildF Not rude Somewhat rude Very rude
No 65.225564 24.060150 10.714286
Yes 82.894737 13.157895 3.947368

Original Plot Code:

mosaicplot(table2p, main="Babies vs parents/nonparents", xlab = "Does the person have children?", ylab = "Is it rude to bring baby aboard")

Modified Code with Custom Colors

The key is using the col parameter in mosaicplot(), which accepts a vector of colors that map directly to the columns in your table (your three rudeness categories are the last three columns here). Here's the updated code:

# Define custom colors for your three categories (order matches table columns)
category_colors <- c("#27AE60", "#F1C40F", "#E74C3C")  # Green, Yellow, Red

# Generate the mosaic plot with custom colors
mosaicplot(table2p, 
           main="Babies vs parents/nonparents", 
           xlab = "Does the person have children?", 
           ylab = "Is it rude to bring baby aboard",
           col = category_colors)

What's Happening Here?

  • The category_colors vector has three colors, one for each of your rudeness categories. The order matters:
    • First color (#27AE60) → "Not rude"
    • Second color (#F1C40F) → "Somewhat rude"
    • Third color (#E74C3C) → "Very rude"
  • You can replace these hex codes with any named R colors (like "green", "orange", "red") or other hex values to match your preferred color scheme.
  • The col parameter applies these colors consistently across both rows ("No" and "Yes") for each corresponding rudeness category.

If you ever need to adjust which categories get which colors, just reorder the values in the category_colors vector to match your table's column order.

内容的提问来源于stack exchange,提问作者helios321

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:10:52