改进这个代码使散点和折线在一张图上生成一张散点折线图:import matplotlib.pyplot as plt # 定义一个函数,用于将实际控制人性质分类为国有和非国有 def gov_or_not(x): gov_list = [1100, 2000, 2100, 2120] if x in gov_list: return '国有' else: return '非国有' # 将实际控制人性质进行分类 df['ownership'] = df['实际控制人性质'].apply(gov_or_not) # 按照企业性质和年份进行分组,计算LSR的均值 lsr_mean = df.groupby(['ownership', '年份'])['LSR'].mean().reset_index() # 分别绘制国有企业和非国有企业的散点图 plt.scatter(lsr_mean[lsr_mean['ownership'] == '国有']['年份'], lsr_mean[lsr_mean['ownership'] == '国有']['LSR'], label='国有企业') plt.scatter(lsr_mean[lsr_mean['ownership'] == '非国有']['年份'], lsr_mean[lsr_mean['ownership'] == '非国有']['LSR'], label='非国有企业') plt.xlabel('年份') plt.ylabel('LSR') plt.legend() plt.show() # 分别绘制国有企业和非国有企业的折线图 plt.plot(lsr_mean[lsr_mean['ownership'] == '国有']['年份'], lsr_mean[lsr_mean['ownership'] == '国有']['LSR'], label='国有企业') plt.plot(lsr_mean[lsr_mean['ownership'] == '非国有']['年份'], lsr_mean[lsr_mean['ownership'] == '非国有']['LSR'], label='非国有企业') plt.xlabel('年份') plt.ylabel('LSR') plt.legend() plt.show()
时间: 2023-09-06 18:13:13 浏览: 118
可以使用plt.plot()函数来绘制折线图,并将两个散点图的绘制代码合并到一起,如下所示:
```
import matplotlib.pyplot as plt
# 定义一个函数,用于将实际控制人性质分类为国有和非国有
def gov_or_not(x):
gov_list = [1100, 2000, 2100, 2120]
if x in gov_list:
return '国有'
else:
return '非国有'
# 将实际控制人性质进行分类
df['ownership'] = df['实际控制人性质'].apply(gov_or_not)
# 按照企业性质和年份进行分组,计算LSR的均值
lsr_mean = df.groupby(['ownership', '年份'])['LSR'].mean().reset_index()
# 绘制散点图和折线图
plt.scatter(lsr_mean[lsr_mean['ownership'] == '国有']['年份'],
lsr_mean[lsr_mean['ownership'] == '国有']['LSR'],
label='国有企业')
plt.plot(lsr_mean[lsr_mean['ownership'] == '国有']['年份'],
lsr_mean[lsr_mean['ownership'] == '国有']['LSR'],
linestyle='-', color='blue')
plt.scatter(lsr_mean[lsr_mean['ownership'] == '非国有']['年份'],
lsr_mean[lsr_mean['ownership'] == '非国有']['LSR'],
label='非国有企业')
plt.plot(lsr_mean[lsr_mean['ownership'] == '非国有']['年份'],
lsr_mean[lsr_mean['ownership'] == '非国有']['LSR'],
linestyle='-', color='green')
plt.xlabel('年份')
plt.ylabel('LSR')
plt.legend()
plt.show()
```
这段代码将两个散点图和两个折线图绘制在同一张图中,其中折线图使用plt.plot()函数绘制,使用linestyle参数设置线条样式,使用color参数设置线条颜色。
阅读全文