首页 > 解决方案 > 在已经绘制的数据上绘制水平线

问题描述

因此,我必须将密度(恒定为 1)绘制到质量与半径以及与重力相关的绘图上。我需要在数据上添加一条线来表示恒定密度。

我试过使用 axhline,但它总是最终使相对于半径的红线变为 1。

%matplotlib notebook
import numpy as np  
import matplotlib.pyplot as plt 

start = 0
end = 1.0
rad_star = np.arange(start,end,0.01)
rho = 1 # constant density
G = 6.67e-11 # gravitational constant
mass = (4.0/3.0)*np.pi*rho*(rad_star)**3
grav = (4*G*np.pi*rho*rad_star)/3

fig = plt.figure()
ax1 = fig.add_subplot(111)
ax2 = ax1.twinx()
ax1.plot(rad_star,mass, 'b-') 
ax2.plot(rad_star,grav, 'r-')
# ax.hline is not working, everytime rho is mentioned, the radius 
line goes directly to one

ax1.set_title("Stellar Interior of Star with Constant Density")
ax1.set_ylabel('Mass ($M/M_{*}$)', color='blue') 
ax2.set_ylabel('Gravity ($g/g_{surface}$)', color='red')
ax1.set_xlabel('Radius ($r/R_{*}$)')
plt.show()

应该是3个地块;一条红色的直线直线,一条蓝色的指数线,一条等于1的黑色线,代表密度。

标签: pythonmatplotlibplot

解决方案


推荐阅读