如何创建年龄vs看电视时长的NumPy随机数组并绘制散点图?
Solution: Generate Age & TV Time Data + Scatter Plot
Got it, let's adjust that code to fit your exact requirements! The original code uses standard normal distribution values (via randn), which don't align with your 18-50 age range and 0-24 hour TV time range. Here's a modified version that generates valid data and produces a clear scatter plot:
Step-by-Step Breakdown
- Import the right libraries: We'll use
numpyfor controlled random data generation andmatplotlib.pyplotfor plotting (more explicit than relying on pylab). - Generate age data: Use
np.random.uniform()to create values uniformly distributed between 18 and 50. We'll cast to integers since ages are typically whole numbers, but you can skip that if you want decimal values. - Generate TV time data: Similarly, use
uniform()to generate values between 0 and 24 hours. - Plot with context: Add axis labels and a title to make the plot meaningful, unlike the bare-bones original.
Full Working Code
import numpy as np import matplotlib.pyplot as plt # Generate 500 random age values (18-50, integer) ages = np.random.uniform(low=18, high=51, size=500).astype(int) # Note: Using high=51 instead of 50 because uniform is exclusive of the upper bound # Generate 500 random daily TV time values (0-24 hours, can be decimal) tv_hours = np.random.uniform(low=0, high=24, size=500) # Create the scatter plot plt.scatter(ages, tv_hours, alpha=0.6) # Alpha adds slight transparency for overlapping points plt.title("Relationship Between Age and Daily TV Watching Time") plt.xlabel("Age (18-50)") plt.ylabel("Daily TV Time (Hours)") plt.xlim(17, 51) # Add small padding to x-axis for better visibility plt.ylim(-0.5, 24.5) # Same for y-axis plt.grid(True, linestyle="--", alpha=0.3) # Add subtle grid for readability # Show the plot plt.show()
Key Notes
- Why
uniform()instead ofrandn()?:randn()produces values centered around 0 with a standard deviation of 1, which doesn't fit your fixed ranges.uniform()generates values evenly spread across your desired interval, which is perfect for this use case. - Integer ages: The
astype(int)converts the float output ofuniform()to whole numbers, which makes sense for age data. If you prefer decimal ages (e.g., 25.5), just remove that part. - Transparency (
alpha): This helps when points overlap, so you can see density in busy areas of the plot.
内容的提问来源于stack exchange,提问作者user6882757
相关产品推荐
相关产品推荐

