PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, June 26, 2022

[FIXED] How to make a graph with x and y of different length

 June 26, 2022     graph, interpolation, matplotlib, python     No comments   

Issue

I'm trying to make a Python app that shows a graph after the input of the data by the user, but the problem is that the y_array and the x_array do not have the same dimensions. When I run the program, this error is raised:

ValueError: x and y must have same first dimension, but have shapes () and ()

How can I draw a graph with the X and Y axis of different length?

Here is a minimal example code that will lead to the same error I got :

import matplotlib.pyplot as plt

y = [0, 8, 9, 3, 0]
x = [1, 2, 3, 4, 5, 6, 7]

plt.plot(x, y)
plt.show()

Solution

This is virtually a copy/paste of the answer found here, but I'll show what I did to get these to match.

First, we need to decide which array to use- the x_array of length 7, or the y_array of length 5. I'll show both, starting with the former. Note that I am using numpy arrays, not lists.

Let's load the modules

import numpy as np
import matplotlib.pyplot as plt
import scipy.interpolate as interp

and the arrays

y = np.array([0, 8, 9, 3, 0])
x = np.array([1, 2, 3, 4, 5, 6, 7])

In both cases, we use interp.interp1d which is described in detail in the documentation.

For the x_array to be reduced to the length of the y_array:

x_inter = interp.interp1d(np.arange(x.size), x)
x_ = x_inter(np.linspace(0,x.size-1,y.size))

print(len(x_), len(y))
# Prints 5,5

plt.plot(x_,y)
plt.show()

Which gives

x_array

and for the y_array to be increased to the length of the x_array:

y_inter = interp.interp1d(np.arange(y.size), y)
y_ = y_inter(np.linspace(0,y.size-1,x.size))

print(len(x), len(y_))
# Prints 7,7
plt.plot(x,y_)
plt.show()

Which gives

y_array



Answered By - t.o.
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing