R语言:diamonds数据集ggplot2直方图Y轴价格显示异常求助
Hey Santosh, I see the issue with your y-axis showing scientific notation instead of actual price values—let's get that sorted out quickly!
First, the reason ggplot switches to scientific notation here is because the price range (up to 20000) triggers its default formatting for large numbers. To override this and force the y-axis to display regular numeric values spanning from 0 to the maximum price in the dataset, you can use scale_y_continuous() with two key arguments:
labels = scales::comma: This formats numbers with commas (e.g., 20000 instead of 2e+04)limits = c(0, max(diamonds$price)): This locks the y-axis range to start at 0 and go up to the highest price in your data
Here's your modified code with these changes:
library(ggplot2) library(scales) # Make sure to load this package for the comma formatter ggplot(data = diamonds, aes(x = cut, y = price)) + geom_histogram(stat = "identity") + scale_y_continuous(labels = comma, limits = c(0, max(diamonds$price)))
Quick Side Note:
Wait a second—using geom_histogram(stat = "identity") with a categorical x-axis (cut) might not be the most intuitive way to visualize this relationship. If you're trying to show the distribution of prices within each cut category, consider switching to geom_boxplot() or geom_violin() instead. If you're looking to display aggregate values (like total or average price per cut), geom_bar() with a summary stat would be better, for example:
# Example: Average price per cut ggplot(data = diamonds, aes(x = cut, y = price)) + geom_bar(stat = "summary", fun = "mean") + scale_y_continuous(labels = comma)
Either way, the scale_y_continuous() trick will fix your scientific notation problem. Let me know if you need further tweaks!
内容的提问来源于stack exchange,提问作者Santosh Gadhave

