Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the simplest python code to plot a simple graph (simpler than matlab)

If I want to draw a y=x^2 graph from 0 to 9 in matlab, I can do

a = [0:1:10]
b = a.^2
plot(a,b)

Using python, I can do the same like below

import matplotlib.pyplot as plt
import numpy as np

a=[x for x in xrange(10)]
b=np.square(a)
plt.plot(a,b)
plt.show()

But to the contrary to my belief that python code is simpler, this takes more lines that matlab. (I guess python tries to make things light weight, so we need to import things when we actually need something, hence more lines..) Can I make above python code simpler(I mean shorter)?

EDIT : I know it doesn't matter and meaningless when it comes to processing time but I was just curious how short the code can become.

like image 541
Chan Kim Avatar asked Aug 14 '16 06:08

Chan Kim


People also ask

Can Python be used to plot graphs?

Graphs in Python can be plotted by using the Matplotlib library. Matplotlib library is mainly used for graph plotting. You need to install matplotlib before using it to plot graphs. Matplotlib is used to draw a simple line, bargraphs, histograms and piecharts.


1 Answers

This is a bit simpler

import matplotlib.pyplot as plt

X = range(10)
plt.plot(X, [x*x for x in X])
plt.show()

but remember that Python is a general purpose language, so it's not surprising it requires a bit more than a specific charting/math tool.

The main clutter is importing the libraries that help about chart plotting and numeric computation, as this is implied for matlab (a tool designed around that).

These lines are however needed only once: they're not a factor, but just an additive constant, going to be negligible even in just slightly more serious examples.

like image 179
6502 Avatar answered Nov 07 '22 04:11

6502