在R语言中指定黑线位置及尺寸绘制条形码的函数求助
Hey David, great question! Yes, you absolutely can create barcodes in R with full control over height, line count (width), and the positions of black bars. Let me share two reliable approaches with you:
If you want complete control over every parameter, writing a quick custom function using base R graphics is perfect. This lets you specify exactly where black bars go, how tall the barcode is, and how many lines (total width) it has.
Here’s a ready-to-use function:
# Custom barcode generator with adjustable parameters draw_barcode <- function(bar_pos, height = 10, line_width = 1, total_width = 50) { # Set up an empty plot canvas plot(0, 0, type = "n", xlim = c(0, total_width), ylim = c(0, height), xlab = "", ylab = "", axes = FALSE) # Calculate the starting x-position for each line line_positions <- seq(0, total_width - line_width, by = line_width) # Draw black bars at your specified positions for (pos in bar_pos) { rect(xleft = line_positions[pos], ybottom = 0, xright = line_positions[pos] + line_width, ytop = height, col = "black") } } # Example: Draw a barcode with black bars at positions 2, 5, 7, 10, 12 draw_barcode(bar_pos = c(2,5,7,10,12), height = 8, line_width = 1, total_width = 20)
What each parameter does:
bar_pos: A vector of indices (e.g.,c(2,5)) marking which lines should be blackheight: The total height of the barcodeline_width: The width of individual barstotal_width: The overall width of the barcode (total lines =total_width / line_width)
If you prefer more polished visuals or want to integrate the barcode into a larger ggplot2 figure, this method works great. It uses geom_rect to draw bars and keeps all parameters adjustable.
First, make sure you have ggplot2 installed (install.packages("ggplot2")), then use this function:
library(ggplot2) ggplot_barcode <- function(bar_pos, height = 10, line_width = 1, total_width = 50) { # Create a data frame with all line positions and their color status lines_df <- data.frame( x_start = seq(0, total_width - line_width, by = line_width), is_black = seq_along(seq(0, total_width - line_width, by = line_width)) %in% bar_pos ) # Build the ggplot2 barcode ggplot(lines_df, aes(xmin = x_start, xmax = x_start + line_width, ymin = 0, ymax = height)) + geom_rect(aes(fill = is_black)) + scale_fill_manual(values = c("white", "black")) + theme_void() + # Remove default axes/background theme(legend.position = "none") + coord_fixed(ratio = total_width / height) # Maintain consistent aspect ratio } # Example: Draw a barcode with thinner bars and taller height ggplot_barcode(bar_pos = c(1,3,6,8,11), height = 12, line_width = 0.8, total_width = 15)
Bonus Note: Standard Barcode Formats
If you need to generate industry-standard barcodes (like UPC, EAN, or Code 128), check out the barcode package. It handles encoding rules automatically, but you can still adjust dimensions using similar parameters to the examples above.
内容的提问来源于stack exchange,提问作者C. DAVID

