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

R中绘制DataFrame直方图出错:如何以distance为X轴、freq为Y轴绘图?

你可以用R语言的base绘图系统或者ggplot2包来实现这个需求,先处理数据里的NA值(第一行freq为NA,会影响绘图),具体操作如下:

数据预览

cis_distance_freq4
# A tibble: 6 × 2
  distance  freq
     <dbl> <dbl>
1        0    NA
2     1000  4380
3    10000  4381
4    40000  4535
5    80000  4536
6  1000000  4558

方法1:Base R 绘图

先清理数据,再绘制图形:

# 移除含NA的行
clean_data <- cis_distance_freq4[!is.na(cis_distance_freq4$freq), ]

# 绘制散点图
plot(x = clean_data$distance, y = clean_data$freq,
     xlab = "distance", ylab = "freq",
     main = "distance与freq关系图",
     pch = 16, col = "darkblue")

# 若需要添加折线连接点,执行以下代码
lines(x = clean_data$distance, y = clean_data$freq, col = "red", lwd = 2)

方法2:ggplot2 绘图(更美观的可视化)

需要先安装并加载ggplot2包:

# 首次使用需安装包
# install.packages("ggplot2")
library(ggplot2)

# 清理数据
clean_data <- cis_distance_freq4[!is.na(cis_distance_freq4$freq), ]

# 散点+折线图示例
ggplot(clean_data, aes(x = distance, y = freq)) +
  geom_line(color = "red", linewidth = 1) +
  geom_point(color = "darkblue", size = 3) +
  labs(x = "distance", y = "freq", title = "distance与freq关系图") +
  theme_minimal()

说明:如果只需要散点图,去掉geom_line部分即可;如果只需要折线图,去掉geom_point部分。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 05:07:11