📜  plt text matplotlib 白色背景 - Python (1)

📅  最后修改于: 2023-12-03 15:33:43.345000             🧑  作者: Mango

plt.text and Matplotlib with a White Background - Python

Matplotlib is a powerful visualization library for Python. However, its default settings have a gray background that might not be appealing to everyone. In this tutorial, we will show you how to change the background color to white and add text to your plots using plt.text().

Setting the Background Color

To change the background color to white, we need to modify the axes.facecolor and figure.facecolor properties. Here is an example:

import matplotlib.pyplot as plt
import numpy as np

# generate some sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)

# create a white figure with a white background
fig, ax = plt.subplots(facecolor='white')
fig.patch.set_facecolor('white')

# plot the data
ax.plot(x, y)

# add a title and axis labels
ax.set_title('Title')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')

# show the plot
plt.show()

First, we create a new figure with a white background by setting facecolor='white'. Then, we plot the data and add a title and axis labels using the set_title(), set_xlabel(), and set_ylabel() methods. Finally, we call plt.show() to display the plot.

Adding Text

To add text to your plot, you can use the plt.text() function. Here is an example:

import matplotlib.pyplot as plt
import numpy as np

# generate some sample data
x = np.linspace(0, 10, 100)
y = np.sin(x)

# create a white figure with a white background
fig, ax = plt.subplots(facecolor='white')
fig.patch.set_facecolor('white')

# plot the data
ax.plot(x, y)

# add a title and axis labels
ax.set_title('Title')
ax.set_xlabel('X Label')
ax.set_ylabel('Y Label')

# add text to the plot
ax.text(3, 0.8, 'Some Text', fontsize=12, color='red')

# show the plot
plt.show()

In this example, we added the text "Some Text" to the plot using ax.text(). The first two arguments are the x and y coordinates of where the text should be placed, and the third argument is the actual text. We also specified the font size and color using the fontsize and color arguments.

That's it! You now know how to change the background color to white and add text to your plots using Matplotlib.