如何在Python中平滑图形中的线条?

2024-02-02

因此,使用下面的代码,我可以绘制一个包含 3 条线的图形,但它们是有角度的。是否可以平滑线条?

import matplotlib.pyplot as plt
import pandas as pd

# Dataframe consist of 3 columns
df['year'] = ['2005, 2005, 2005, 2015, 2015, 2015, 2030, 2030, 2030']
df['name'] = ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C']
df['weight'] = [80, 65, 88, 65, 60, 70, 60, 55, 65]
fig,ax = plt.subplots()

# plot figure to see how the weight develops through the years
for name in ['A','B','C']:
    ax.plot(df[df.name==name].year,df[df.name==name].weight,label=name)

ax.set_xlabel("year")
ax.set_ylabel("weight")
ax.legend(loc='best')

您应该对数据应用插值,并且它不应该是“线性”的。这里我使用 scipy 应用了“三次”插值interp1d。另请注意,要使用三次插值,您的数据应至少有 4 个点。因此,我又添加了 2031 年和所有权重的另一个值(我通过从最后一个权重值中减去 1 得到新的权重值):

这是代码:

import matplotlib.pyplot as plt
import pandas as pd
from scipy.interpolate import interp1d
import numpy as np

# df['year'] = ['2005, 2005, 2005, 2015, 2015, 2015, 2030, 2030, 2030']
# df['name'] = ['A', 'B', 'C', 'A', 'B', 'C', 'A', 'B', 'C']
# df['weight'] = [80, 65, 88, 65, 60, 70, 60, 55, 65]

df1 = pd.DataFrame()
df1['Weight_A'] = [80, 65,  60 ,59]
df1['Weight_B'] = [65, 60,  55 ,54]
df1['Weight_C'] = [88, 70,  65 ,64]
df1.index = [2005,2015,2030,2031]


ax = df1.plot.line()
ax.set_title('Before interpolation')
ax.set_xlabel("year")
ax.set_ylabel("weight")

f1 = interp1d(df1.index, df1['Weight_A'],kind='cubic')
f2 = interp1d(df1.index, df1['Weight_B'],kind='cubic')
f3 = interp1d(df1.index, df1['Weight_C'],kind='cubic')

df2 = pd.DataFrame()
new_index = np.arange(2005,2031)
df2['Weight_A'] = f1(new_index)
df2['Weight_B'] = f2(new_index)
df2['Weight_C'] = f3(new_index)
df2.index = new_index

ax2 = df2.plot.line()
ax2.set_title('After interpolation')
ax2.set_xlabel("year")
ax2.set_ylabel("weight")


plt.show()

结果:

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在Python中平滑图形中的线条? 的相关文章

  • 使用 matplotlib 绘制时间序列数据并仅在年初显示年份

    rcParams date autoformatter month b n Y 我正在使用 matpltolib 来绘制时间序列 如果我按上述方式设置 rcParams 则生成的图会在每个刻度处标记月份名称和年份 我怎样才能将其设置为仅在每
  • 如何替换 pandas 数据框列中的重音符号

    我有一个数据框dataSwiss其中包含瑞士城市的信息 我想用普通字母替换带有重音符号的字母 这就是我正在做的 dataSwiss Municipality dataSwiss Municipality str encode utf 8 d
  • 是否可以忽略一行的pyright检查?

    我需要忽略一行的pyright 检查 有什么特别的评论吗 def create slog group SLogGroup data Optional dict None SLog insert one SLog group group da
  • 测试 python Counter 是否包含在另一个 Counter 中

    如何测试是否是pythonCounter https docs python org 2 library collections html collections Counter is 包含在另一个中使用以下定义 柜台a包含在计数器中b当且
  • ipython/ pylab/ matplotlib安装和初始化错误

    我在 OS X El Captain 上安装了 matplotlib anaconda ipython 然而 即使在尝试以所有可能的方式设置环境变量之后 我仍无法启动 ipython shell pylab 版本 这是错误 ImportEr
  • 从 Flask 访问 Heroku 变量

    我已经使用以下命令在 Heroku 配置中设置了数据库变量 heroku config add server xxx xxx xxx xxx heroku config add user userName heroku config add
  • 如何在Python中获取葡萄牙语字符?

    我正在研究葡萄牙语 角色看起来很奇怪 我怎样才能解决这个问题 代码 import feedparser import random Vou definir os feeds feeds conf feedurl http pplware s
  • 添加不同形状的 numpy 数组

    我想添加两个不同形状的 numpy 数组 但不进行广播 而是将 缺失 值视为零 可能最简单的例子是 1 2 3 2 gt 3 2 3 or 1 2 3 2 1 gt 3 2 3 1 0 0 我事先不知道形状 我正在弄乱每个 np shape
  • 如何在ipywidget按钮中显示全文?

    我正在创建一个ipywidget带有一些文本的按钮 但按钮中未显示全文 我使用的代码如下 import ipywidgets as widgets from IPython display import display button wid
  • IO 密集型任务中的 Python 多线程

    建议仅在 IO 密集型任务中使用 Python 多线程 因为 Python 有一个全局解释器锁 GIL 只允许一个线程持有 Python 解释器的控制权 然而 多线程对于 IO 密集型操作有意义吗 https stackoverflow c
  • python获取上传/下载速度

    我想在我的计算机上监控上传和下载速度 一个名为 conky 的程序已经在 conky conf 中执行了以下操作 Connection quality alignr wireless link qual perc wlan0 downspe
  • 在 MatPlotLib 中检索自定义破折号

    关于如何使用 matplotlib 线中设置自定义破折号有很多问题Line2D set linestyle and Line2D set dashes 但是 我似乎找不到在设置后检索破折号图案的方法 这是在主站点上设置破折号的示例 我将在下
  • 将图像分割成多个网格

    我使用下面的代码将图像分割成网格的 20 个相等的部分 import cv2 im cv2 imread apple jpg im cv2 resize im 1000 500 imgwidth im shape 0 imgheight i
  • Python:如何将列表列表的元素转换为无向图?

    我有一个程序 可以检索 PubMed 出版物列表 并希望构建一个共同作者图 这意味着对于每篇文章 我想将每个作者 如果尚未存在 添加为顶点 并添加无向边 或增加每个合著者之间的权重 我设法编写了第一个程序 该程序检索每个出版物的作者列表 并
  • 发送用户注册密码,django-allauth

    我在 django 应用程序上使用 django alluth 进行身份验证 注册 我需要创建一个自定义注册表单 其中只有一个字段 电子邮件 密码将在服务器上生成 这是我创建的表格 from django import forms from
  • Rocket UniData/UniVerse:ODBC 无法分配足够的内存

    每当我尝试使用pyodbc连接到 Rocket UniData UniVerse 数据时我不断遇到错误 pyodbc Error 00000 00000 Rocket U2 U2ODBC 0302810 Unable to allocate
  • Python 类继承 - 诡异的动作

    我观察到类继承有一个奇怪的效果 对于我正在处理的项目 我正在创建一个类来充当另一个模块的类的包装器 我正在使用第 3 方 aeidon 模块 用于操作字幕文件 但问题可能不太具体 以下是您通常如何使用该模块 project aeidon P
  • 线性判别分析图

    如何将样本 ID 行号 作为标签添加到此 LDA 图中的每个点 library MASS ldaobject lt lda Species data iris plot ldaobject panel function x y points
  • Python Selenium:如何在文本文件中打印网站上的值?

    我正在尝试编写一个脚本 该脚本将从 tulsaspca org 网站获取以下 6 个值并将其打印在 txt 文件中 最终输出应该是 905 4896 7105 23194 1004 42000 放置的动物 的 HTML span class
  • 如何将输入读取为数字?

    这个问题的答案是社区努力 help privileges edit community wiki 编辑现有答案以改进这篇文章 目前不接受新的答案或互动 Why are x and y下面的代码中使用字符串而不是整数 注意 在Python 2

随机推荐