python使用matplotlib画散点图,让Y轴位置在X轴的中间
时间: 2024-03-01 17:53:35 浏览: 141
可以使用`set_ylim`和`set_yticks`函数来设置Y轴的位置和刻度。具体代码如下:
```python
import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [5, 3, 2, 4, 1]
fig, ax = plt.subplots()
ax.scatter(x, y)
# 设置Y轴位置在X轴的中间
ax.spines['left'].set_position(('data', len(x)/2))
ax.spines['left'].set_color('none')
ax.yaxis.tick_right()
# 设置Y轴刻度
y_ticks = ax.get_yticks()
ax.set_yticks(y_ticks[1:-1])
plt.show()
```
在上面的代码中,使用`plt.subplots()`函数创建一个包含一个子图的画布和子图对象。然后使用`ax.scatter()`函数绘制散点图。接着使用`ax.spines`和`ax.yaxis`函数设置Y轴的位置和刻度。最后使用`plt.show()`函数显示图形。
相关问题
python使用matplotlib画散点图,让坐标刻度固定为±10间隔1
好的,下面是代码示例:
```python
import matplotlib.pyplot as plt
# 生成随机散点数据
import numpy as np
np.random.seed(0)
x = np.random.uniform(-10, 10, size=100)
y = np.random.uniform(-10, 10, size=100)
# 绘制散点图
fig, ax = plt.subplots()
ax.scatter(x, y)
# 设置坐标轴范围和刻度
ax.set_xlim([-10, 10])
ax.set_ylim([-10, 10])
ax.set_xticks(np.arange(-10, 11, 1))
ax.set_yticks(np.arange(-10, 11, 1))
# 显示图像
plt.show()
```
其中,`np.arange(-10, 11, 1)` 表示在 $[-10, 10]$ 范围内,以步长为 1 生成一个数组,即 $-10,-9,-8,...,9,10$。`ax.set_xticks()` 和 `ax.set_yticks()` 分别设置 x 轴和 y 轴的刻度。
python画散点图-Python:matplotlib绘制散点图
好的,很高兴为您解答。下面是Python使用matplotlib库绘制散点图的基本代码:
```python
import matplotlib.pyplot as plt
import numpy as np
# 生成随机数据
x = np.random.rand(50)
y = np.random.rand(50)
# 绘制散点图
plt.scatter(x, y)
# 设置图形属性
plt.title('Scatter Plot')
plt.xlabel('X-axis')
plt.ylabel('Y-axis')
# 显示图形
plt.show()
```
代码解释:
1. 导入matplotlib库和numpy库。
2. 使用numpy库生成两个长度为50的一维随机数组x和y。
3. 使用plt.scatter()函数绘制散点图,传入x和y数组作为参数。
4. 使用plt.title()、plt.xlabel()和plt.ylabel()函数设置图形的标题、X轴标签和Y轴标签。
5. 使用plt.show()函数显示图形。
您可以根据需要修改代码,例如更改数据生成方式、调整图形属性等。希望能对您有所帮助!
阅读全文
相关推荐













