优化下面代码import matplotlib.pyplot as plt import numpy as np fig = plt.figure(figsize=(22 / 2.54, 18 / 2.54), facecolor='white', edgecolor='w', linewidth=2) plt.rcParams['xtick.direction'] = 'in' plt.rcParams['ytick.direction'] = 'in' ax = plt.gca() x = np.linspace(0, 12, 12) y = np.random.random(len(x)) * 16.5 + 6 p1, = plt.plot(x, y, '>', color='orange') p2, = plt.plot(x, y, '-', color='cyan') plt.title('深圳市24小时的平均风速', fontfamily='SimSun', fontsize=12) # fontstyle="italic" 斜体 ax.set_xlabel('时间(h)', fontfamily='SimSun') ax.set_ylabel('平均风速(km/h)', fontfamily='SimSun') ax.xaxis.set_ticks(np.linspace(0, 12, 13)) ax.yaxis.set_ticks(np.linspace(8, 22, 8)) ax.xaxis.set_ticklabels(['00:00', '02:00', '04:00', '06:00', '08:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00', '00:00'], rotation=45) plt.savefig('fig.pdf') plt.show()
时间: 2023-06-16 13:03:08 浏览: 297
import numpy as np import matplotlib.pyplot as plt import math
Here is the optimized code:
```python
import matplotlib.pyplot as plt
import numpy as np
plt.rcParams['xtick.direction'] = 'in'
plt.rcParams['ytick.direction'] = 'in'
x = np.linspace(0, 12, 12)
y = np.random.random(len(x)) * 16.5 + 6
fig, ax = plt.subplots(figsize=(22/2.54, 18/2.54), facecolor='white', edgecolor='w', linewidth=2)
ax.plot(x, y, '>', color='orange', label='平均风速')
ax.plot(x, y, '-', color='cyan', label='平均风速')
ax.set_title('深圳市24小时的平均风速', fontfamily='SimSun', fontsize=12)
ax.set_xlabel('时间(h)', fontfamily='SimSun')
ax.set_ylabel('平均风速(km/h)', fontfamily='SimSun')
ax.set_xticks(np.arange(0, 13, 2))
ax.set_yticks(np.arange(8, 23, 2))
ax.set_xticklabels(['00:00', '02:00', '04:00', '06:00', '08:00', '10:00', '12:00', '14:00', '16:00', '18:00', '20:00', '22:00', '00:00'], rotation=45)
ax.legend(loc='best')
plt.savefig('fig.pdf')
plt.show()
```
In this optimized code, we:
- Use `subplots` to create a figure and axes instance at the same time.
- Add labels to the `plot` function to create a legend for the plot.
- Use `np.arange` instead of `np.linspace` to set the tick locations for the x and y axis.
- Use `ax.legend` to add a legend to the plot.
阅读全文