import matplotlib.pyplot as plt
import numpy as np
np.random.seed(42)
num_bars=50
bar_positions=np.arange(num_bars)
bar_widths=np.random.choice([0.1,0.2,0.3,0.4],size=num_bars)
bar_heights=np.ones(num_bars)
fig,ax=plt.subplots(figsize=(10,5))
ax.bar(bar_positions,bar_heights,width=bar_widths,color="black")
ax.set_xticks([])
ax.set_yticks([])
ax.spines['top'].set_visible(False)
ax.spines['bottom'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['right'].set_visible(False)
plt.title("Barcode like pattern")
plt.show()
#source code --> clcoding.com
Code Explanation:
1. Import Required Libraries
import numpy as np
import matplotlib.pyplot as plt
numpy: Used to generate random numbers and create an
array of positions.
matplotlib.pyplot: Used to create and display the
plot.
np.random.seed(42)
Ensures the same random numbers are generated every
time the code runs.
num_bars = 50
Specifies 50 vertical bars to be plotted.
bar_positions = np.arange(num_bars)
Creates an array [0, 1, 2, ..., 49] to specify the
position of each bar along the x-axis.
bar_widths = np.random.choice([0.1, 0.2, 0.3, 0.4],
size=num_bars)
Randomly selects bar widths from [0.1, 0.2, 0.3,
0.4] for each bar, adding variation.
bar_heights = np.ones(num_bars)
Sets all bars to the same height of 1 (uniform
height).
fig, ax = plt.subplots(figsize=(10, 5))
Creates a figure (fig) and an axis (ax) with a 10x5
aspect ratio for better visibility.
ax.bar(bar_positions, bar_heights, width=bar_widths,
color='black')
Plots the bars at bar_positions with:
bar_heights = 1 (uniform height)
bar_widths (randomly chosen for variation)
Black color, to resemble a barcode.
ax.set_xticks([])
ax.set_yticks([])
Hides x-axis and y-axis ticks to give a clean
barcode appearance.
ax.spines['top'].set_visible(False)
ax.spines['right'].set_visible(False)
ax.spines['left'].set_visible(False)
ax.spines['bottom'].set_visible(False)
Hides the top, right, left, and bottom borders
(spines) of the plot.
plt.show()
Renders and displays the barcode-like pattern.
0 Comments:
Post a Comment