How to connect dots with a line in real time using matplotlib - python

I'm writting a "3x+1" simulation code using matplotlib just for fun. I'm trying to make the values appear in real time and connected by a line. But I only get the scatter dots.
Code:
import matplotlib.pyplot as plt
plots = []
def three(x):
if x == 1:
return x
if x % 2 == 0:
plots.append(x/2)
return three(x/2)
else:
plots.append(3*x+1)
return three(3*x+1)
num = int(input('Number: '))
plots.append(num)
three(num)
y = []
x = [x for x in range(len(plots)+1)]
x.pop(0)
for i in plots:
plt.plot(x[plots.index(i)], i, ".-")
plt.pause(0.05)
plt.show()

Could you try this? I am thinking the render of plt.Show is occurring after all the pauses are looped. edit- sorry I see now you are asking about connecting the plots.
for i in plots:
plt.plot(x[plots.index(i)], i, ".-")
plt.pause(0.05)
plt.show()
I think your marker string is wrong found here. Try this
plt.plot(x[plots.index(i)], i, "-.")

Related

Merge multiple matplotlib charts into a single chart and assign color based on array

New to coding so please bear with me. I was trying to merge multiple matplotlib charts into one and based on the value of array 'z' auto assign a color.
import random
import matplotlib.pyplot as plt
z = []
x1 = []
y1 = []
for u in range(10):
z.append(round(random.uniform(1,40),0))
for i in range(30):
x1.append(i)
for x in z:
print(x)
for i in range(30):
if x%2 == 0:
x = x / 2
else:
x = x*3 + 1
y1.append(x)
plt.plot(x1,y1)
plt.show()
y1 = []
Effectively, I want to play around with values of iterants and not manually define color each time. Help is sincerely appreciated!

Plot doesn't appear after using plt.plot

I have this code:
from matplotlib.pylab import plt
abc = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',]
def countp(counter):
count=0
for i in counter:
print(abc[count],"showed up ",i," times")
count+=1
def checkfile(folder):
file = open(folder,"r")
read=file
abc = ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z',]
counter = [0]*26
#read file
for i in file:
# reads line
for j in i:
count=0
#search one key at a time
for k in abc:
if (j==k.lower()):
#add +1 to desired letter.
counter[count]+=1
count+=1
return counter
if __name__ == "__main__":
folder="C:/Users/omerd/Desktop/Welp.txt"
counter=checkfile(folder)
countp(counter)
x=5
y=6
plt.plot(x, y)
it does run, but it doesn't use the
plt.plot(x, y)
line. It should open a chart, but it doesn't, not sure if newbie mistake or need to reinstall everything.
Many Documentations Don't mention this but try adding plt.show() at the after plt.plot().
plt.show() is just to open the matplotlib plot
The solution to your problem is to add plt.show() at the end of your code. This will display your plot.
From matplotlib's official documentation: When running in ipython with its pylab mode, display all figures and return to the ipython prompt.

Python Matplotlib Multicursor: Show value under cursor in legend

I am using Multicursor to get a cursor on every graph.
I want to show the value of the datapoint, which is hit by the cursor, inside a legend during hovering over the graphs, like this
Actually I have thought that this is a standard feature of matplotlib respectively Multicursor, but it seems not. Did someone already something like this or do I have to implement it by my own.
I already found this post matplotlib multiple values under cursor, but this could be just the beginning for the implementation I want.
I have developed a solution.
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.widgets import MultiCursor
from bisect import bisect_left
fig = plt.figure(figsize=(15, 8))
# create random graph with 60 datapoints, 0 till 59
x = list(range(0,60))
axes_list = []
def createRandomGraph(ax,x):
y = np.random.randint(low=0, high=15, size=60)
data.append(y)
ax.plot(x,y, marker='.')
def take_closest(myList, myNumber):
"""
Assumes myList is sorted. Returns closest value to myNumber.
If two numbers are equally close, return the smallest number.
"""
pos = bisect_left(myList, myNumber)
if pos == 0:
return myList[0]
if pos == len(myList):
return myList[-1]
before = myList[pos - 1]
after = myList[pos]
if after - myNumber < myNumber - before:
return after, pos
else:
return before, pos-1
def show_Legend(event):
#get mouse coordinates
mouseXdata = event.xdata
# the value of the closest data point to the current mouse position shall be shown
closestXValue, posClosestXvalue = take_closest(data[0], mouseXdata)
i = 1
for ax in axes_list:
datalegend = ax.text(1.05, 0.5, data[i][posClosestXvalue], fontsize=7,
verticalalignment='top', bbox=props, transform=ax.transAxes)
ax.draw_artist(datalegend)
# this remove is required because otherwise after a resizing of the window there is
# an artifact of the last label, which lies behind the new one
datalegend.remove()
i +=1
fig.canvas.update()
# store the x value of the graph in the first element of the list
data = [x]
# properties of the legend labels
props = dict(boxstyle='round', edgecolor='black', facecolor='wheat', alpha=1.5)
for i in range(5):
if(i>0):
# all plots share the same x axes, thus during zooming and panning
# we will see always the same x section of each graph
ax = plt.subplot(5, 1, i+1, sharex=ax)
else:
ax = plt.subplot(5, 1, i+1)
axes_list.append(ax)
createRandomGraph(ax,x)
multi = MultiCursor(fig.canvas, axes_list, color='r', lw=1)
# function show_Legend is called while hovering over the graphs
fig.canvas.mpl_connect('motion_notify_event', show_Legend)
plt.show()
The output looks like this
Maybe you like it and find it useful

Pyplot Not Displaying My Graph

I'm trying to graph the recaman sequence as a scatter plot and as far as I can tell my script is setup correctly. Also I'm pretty sure its not the back-end because I can run scripts like:
import matplotlib.pyplot as plt
plt.plot([1,2,3,4])
plt.ylabel('some numbers')
plt.show()
and it works fine. Here's what my code looks like:
import matplotlib.pyplot as plt
import os
while(True):
try:
itterations = int(input("Itterations: "))
break
except ValueError:
os.system("cls")
def recaman(n):
arr = [0] * n
arr[0] = 0
for i in range(1, n):
curr = arr[i-1] - i
for j in range(0, i):
if ((arr[j] == curr) or curr < 0):
curr = arr[i-1] + i
break
arr[i] = curr
return(arr)
def genX(n):
x = []
for i in range(0,n):
i += 1
x.append(i)
return(x)
xaxis = genX(itterations)
yaxis = recaman(itterations)
for i in range (0,itterations):
plt.plot(xaxis[i],yaxis[i])
plt.show()
Instead of plotting individual invisible points in the loop, plot the whole curve with plt.plot(xaxis,yaxis) or (better) plt.scatter(xaxis,yaxis).
If you prefer to plot the individual points, at least make them visible:
for i in range (0,itterations):
plt.plot(xaxis[i],yaxis[i],"o")
plt.show()

Matplotlib update a graph with new data, graph does not show

I have much the same problem as this guy: Dynamically updating plot in matplotlib. I want to update a graph with data from a serial port and I have been trying to implement this answer, but I can't get a MWE to work. The graph simply doesn't appear, but everything else seems to work. I have read about problems with the installation of Matplotlib causing similar symptoms.
Here is my Minimum Not Working Example (MNWE):
import numpy as np
import matplotlib.pyplot as plt
fig1 = plt.figure() #Create figure
l, = plt.plot([], [], 'r-') #What is the comma for? Is l some kind of struct/class?
plt.xlim(0, 1)
plt.ylim(0, 1)
plt.xlabel('x')
plt.title('test')
k = 5
xdata=[0.5 for i in range(k+1)] # Generate a list to hold data
ydata=[j for j in range(k+1)]
while True:
y = float(raw_input("y val :"))
xdata.append(y) # Append new data to list
k = k + 1 # inc x value
ydata.append(k)
l.set_data(xdata,ydata) # update data
print xdata # Print for debug perposes
print ydata
plt.draw # These seem to do nothing
plt.show # !?
Could someone please point me in the right direction / provide a link / tell me what to google? I'm lost. Thanks
As suggested by user #fhdrsdg I was missing brackets. Getting the rescale to work requires code from: set_data and autoscale_view matplotlib
A working MWE is provided below:
import numpy as np
import matplotlib.pyplot as plt
plt.ion() # Enable interactive mode
fig = plt.figure() # Create figure
axes = fig.add_subplot(111) # Add subplot (dont worry only one plot appears)
axes.set_autoscale_on(True) # enable autoscale
axes.autoscale_view(True,True,True)
l, = plt.plot([], [], 'r-') # Plot blank data
plt.xlabel('x') # Set up axes
plt.title('test')
k = 5
xdata=[0.5 for i in range(k+1)] # Generate a list to hold data
ydata=[j for j in range(k+1)]
while True:
y = float(raw_input("y val :")) #Get new data
xdata.append(y) # Append new data to list
k = k + 1 # inc x value
ydata.append(k)
l.set_data(ydata,xdata) # update data
print xdata # Print for debug perposes
print ydata
axes.relim() # Recalculate limits
axes.autoscale_view(True,True,True) #Autoscale
plt.draw() # Redraw

Categories