#matplotlib #python #programming #question #visualization #intermediate
Write a Python program using matplotlib to perform the following tasks:
1. Generate two arrays: x from 0 to 10 with 100 points, and y = sin(x) + 0.5 * cos(2x).
2. Create a figure with two subplots arranged vertically.
3. In the first subplot, plot y vs x as a line graph with red color and marker 'o'.
4. In the second subplot, create a histogram of the y values with 20 bins.
5. Add titles, labels, and grid to both subplots.
6. Adjust the layout and save the figure as 'output_plot.png'.
Note: This code generates a sine wave with an added cosine component, creates a line plot and histogram of the data in separate subplots, adds appropriate labels and grids, and saves the resulting visualization.
By: @DataScienceQ 🚀
Write a Python program using matplotlib to perform the following tasks:
1. Generate two arrays: x from 0 to 10 with 100 points, and y = sin(x) + 0.5 * cos(2x).
2. Create a figure with two subplots arranged vertically.
3. In the first subplot, plot y vs x as a line graph with red color and marker 'o'.
4. In the second subplot, create a histogram of the y values with 20 bins.
5. Add titles, labels, and grid to both subplots.
6. Adjust the layout and save the figure as 'output_plot.png'.
import numpy as np
import matplotlib.pyplot as plt
# 1. Generate data
x = np.linspace(0, 10, 100)
y = np.sin(x) + 0.5 * np.cos(2 * x)
# 2. Create figure with two subplots
fig, (ax1, ax2) = plt.subplots(2, 1, figsize=(8, 10))
# 3. First subplot - line plot
ax1.plot(x, y, color='red', marker='o', linestyle='-', linewidth=2)
ax1.set_title('sin(x) + 0.5*cos(2x)')
ax1.set_xlabel('x')
ax1.set_ylabel('y')
ax1.grid(True)
# 4. Second subplot - histogram
ax2.hist(y, bins=20, color='blue', alpha=0.7)
ax2.set_title('Histogram of y values')
ax2.set_xlabel('y')
ax2.set_ylabel('Frequency')
ax2.grid(True)
# 5. Adjust layout
plt.tight_layout()
# 6. Save the figure
plt.savefig('output_plot.png')
print("Plot saved as 'output_plot.png'")
Note: This code generates a sine wave with an added cosine component, creates a line plot and histogram of the data in separate subplots, adds appropriate labels and grids, and saves the resulting visualization.
By: @DataScienceQ 🚀