Instagram
youtube
Facebook
Twitter

Modify Plot Background and Grid Style

Description:
This program changes the background color of the plot and the figure, and customizes the grid lines to improve readability.

 

Explanation:

  • fig.patch.set_facecolor() sets the outer background color of the figure.

  • ax.set_facecolor() sets the inner plot (chart area) background color.

  • ax.plot() draws the line chart.

  • ax.grid() adds grid lines with custom style (-- dashed lines), color, and transparency (alpha).

  • set_title(), set_xlabel(), and set_ylabel() label the chart.

  • plt.show() displays the chart with the new background and grid style.


Program:

import matplotlib.pyplot as plt

# Sample data
x = [1, 2, 3, 4, 5]
y = [5, 10, 15, 20, 18]

# Create the plot
fig, ax = plt.subplots()

# Modify background color
fig.patch.set_facecolor('#f0f0f0')        # Outside plot background
ax.set_facecolor('#ffffff')               # Inside plot background

# Plot data
ax.plot(x, y, color='blue', marker='o')

# Customize grid
ax.grid(True, linestyle='--', color='gray', alpha=0.7)

# Add titles and labels
ax.set_title('Modified Background & Grid Style')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')

# Show plot
plt.show()


Output: