# Create and plot fix of slopes between points

4

Good afternoon everyone, I'm trying to create an array with `numpy` that contains the slope between each of the points made with the arrays `x` e `y` to finally graph them with `matplotlib` .

These are the steps that I am currently following:

1. I calculate the slope for each of the points.

2. I add each calculated slope to a list.

3. The resulting list is transformed into an array of `numpy` .

4. Graph that array with matplotlib.

This is my code:

``````#!/usr/bin/python
# -*- coding: utf-8 -*-
import numpy as np
import matplotlib.pyplot as plt
x = np.array([0,1,2,3,4,5,6])
y = np.array([0,1,2,3,2,1,0])
lista = []
for i in range(len(x)-1):
dy = (y[i+1]-y[i]) / (x[i+1] - x[i])
lista.append(dy)
pendiente = np.asarray(lista)
ejex = len(x)-1
plt.plot(ejex,pendiente,'-m')
plt.show()
``````

Does anyone know a better way to do this?

Thank you very much.

asked by Carlos Hernandez 25.01.2016 в 00:33
source

5

You could use np.diff for the differences and Then do the division. The result is a `numpy.ndarray` , so you do not have to convert it.

``````import numpy as np
import matplotlib.pyplot as plt
x = np.array([0,1,2,3,4,5,6])
y = np.array([0,1,2,3,2,1,0])
pendiente = np.diff(y) / np.diff(x)
plt.plot(pendiente, '-m')
plt.show()
``````