如何解决如何更改绘图的轴依据? Python,Matplotlib
我想创建一个2 *高度(即索引中的米值)与时间平方(即列中的十进制值)的图形。我该怎么做呢? (在matplotlib中)
为清楚起见,我希望y轴为2 *索引值,x轴为列中的时间平方。我希望这是一系列折线图
解决方法
import matplotlib.pyplot as plt
plt.plot(list of things on x-axis,list of things on y-axs)
plt.show
,
import matplotlib.pyplot as plt
plt.plot(times_squared_variable,2_height_variable,'--',color='choose_a_color')
# Label axis and the plot
plt.xlabel('Name_x_axis')
plt.ylabel('Name_y_axis')
plt.title('Plot_name')
# Show the plot
plt.show()
,
在评论中,您说您使用df1.plot()
画线。 df.plot()
默认使用数据框索引作为x值。您说,您希望y轴是2 *索引值,而x轴则是列中的时间平方。您的需求涉及更改数据框值,因此建议您使用ax.plot()
进行更好的自定义。
这是一个使用numpy.linalg.lstsq的程序,该程序内部采用Least squares来获取给定点之间的匹配线。
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from io import StringIO
TESTDATA = StringIO("""Height Trial:1 Trial:2 Trial:3 Trial:4 Trial:5 Trial:6 Trial:7
1.029 0.4667 0.4616 0.4569 0.4579 0.4653 0.4578 0.4484
1.095 0.4752 0.4773 0.4721 0.4738 0.4713 0.4745 0.4663
1.168 0.4836 0.4834 0.4873 0.4890 0.4890 0.4904 0.4902
1.315 0.5139 0.5117 0.5161 0.5108 0.5224 0.5129 0.5187
1.540 0.5644 0.5677 0.5804 0.5535 0.5636 0.5605 0.5609
1.807 0.6051 0.6124 0.6014 0.6035 0.5977 0.6012 0.6209
""")
df = pd.read_csv(TESTDATA,delim_whitespace=True)
df.set_index(['Height'],inplace=True)
fig,ax = plt.subplots()
for column in df:
x = df[column]**2
y = df.index*2
A = np.vstack([x,np.ones(len(x))]).T
k,b = np.linalg.lstsq(A,y)[0]
line = ax.plot(x,y,'o')
ax.plot(x,k*x+b,label=f'y={k:.5f}x+{b:.5f}',color=line[0].get_color(),linestyle='dashed')
plt.legend()
plt.xlabel('Fall time,squared (s²)')
plt.ylabel('Twice the height (m)')
plt.title('Measurement of Acceleration due to Gravity on Earth')
plt.show()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。