I'm VERY new to Python (been working in it for only a day and with no previous programming experience), and for a project I'm looking to make a histogram within a dedicated window in an existing GUI. At this point I'm just looking for it to contain randomly generated data. I'm using pyqtgraph, numpy, and Python 3.
I've been trying to rework this code which i got to work and creates a scatter plot with random data and places it within my GUI window:
def upd_lowerplot1(self):
""" Function to update bottom plot 1. """
# Clear Plot
self.ui.ui_botplot1.clear()
# Now generate the plot
x = np.random.normal(size=1000)
y = np.random.normal(size=1000)
self.ui.ui_botplot1.plot(x, y, pen=None, symbol='o')
I haven't found any examples on here or elsewhere that make much sense to me. If anyone could walk me through how to alter this code in baby steps that would be fantastic, trying to learn, not just get an answer with no understanding.
Related
I have a XV-11 Lidar sensor from an old vacuum cleaner and I want to use it for a robot project.
During my research, I saw a very interesting and simple approach using Matplotlib and display all the distances using scatter points. eg (https://udayankumar.com/2018/08/01/working-with-lidar/) but when I run this python code to RP3 indeed a Matplotlib window is popping up with all the distances but the refresh rate for data it's too slow and impossible to view in real time. I mean the matplotlib display is falling behind a few dozens of seconds with all the sensor readings.
My next idea was to do something by myself with the following display lines but I have same result: Good readings but delayed a lot.
points =[]
plt.ion()
x = dist_mm*np.cos(angle_rad)
y = dist_mm*np.sin(angle_rad)
points.append([x,y])
points = np.array(points)
plt.scatter(points[:,0], points[:,1])
if angle == 356:
plt.plot()
plt.draw()
plt.pause(0.0001)
plt.clf()
print ("-----------")
What I'm doing wrong or what I can improve in this case? My expectations are something like this
Lidar animation, source: https://github.com/Hyun-je/pyrplidar but in this example it's used a different Lidar sensor
You are clearing and re-creating the axes, background etc. every time. At the very least you can limit this drawing/re-drawing to only the relevant plot points for a degree of improvement.
If you're not familiar with this I'd start with the animation guidance- https://matplotlib.org/stable/api/animation_api.html which introduces some basics like updating only parts of the figure.
If you're still churning out too much data to update then limiting the frequency with which you read your data or more specifically the rate at which you redraw might result in more stability too.
Probably worth hunting down more general guidance on realtime plotting e.g. update frame in matplotlib with live camera preview
I want to plot a multiparite graph using networkx. However, when adding more nodes, the plot becomes very crowdy. Is there a way to have more space between nodes and partitions?
Looking at the documentation of multipartite_layout, I couldn't find parameters for this.
Of course, one could create complicated formulas for the positions, but since the spacing of multipartite_layout already looks so good for small graphs, I was how to scale this to bigger graphs.
Has anyone an idea how to do this (efficiently)?
Sample code, generating a graph with three partitions:
import matplotlib.pyplot as plt
import networkx as nx
# build graph:
G = nx.Graph()
for i in range (0,30):
G.add_node(i,layer=0)
for i in range (30,50):
G.add_node(i,layer=1)
for j in range(0,30):
G.add_edge(i,j)
G.add_node(100,layer=2)
G.add_edge(40,100)
# plot graph
pos = nx.multipartite_layout(G, subset_key="layer",)
plt.figure(figsize=(20, 8))
nx.draw(G, pos,with_labels=False)
plt.axis("equal")
plt.show()
The current, crowdy plot:
nx.multipartite_layout returns a dictionary with the following format: {node: array([x, y])}
I suggest you try pos = {p:array_op(pos[p]) for p in pos} where array_op is a function acting on the position of each node, array([x, y]).
In your case, I think a simple scaling along the x-axis suffice, i.e.
array_op = lambda x, sx: np.array(x[0]*sx, x[1]).
For visualization purpose I guess this should be equivalent with #JPM 's comment. However, this approach gives you the advantage of having the actual transformed position data.
In the end, if such uniform transformation does not satisfy your need, you can always manipulate the position manually with the knowledge of the format of the dict (although it might be less efficient).
This question already has answers here:
How to change spacing between ticks
(4 answers)
Closed 5 months ago.
I'am kind of in a rush to finish this for tomorrows presentation towards the project owner. We are a small group of economic students in germany trying to figure out machine learning with python. We set up a Random Forest Classifier and are desperate to show the estimators important features in a neat plot. By applying google search we came up with the following solution that kind of does the trick, but leaves us unsatisfied due to the overlapping of the labels on the y-axis. The code we used looks like this:
feature_importances = clf.best_estimator_.feature_importances_
feature_importances = 100 * (feature_importances / feature_importances.max())
sorted_idx = np.argsort(feature_importances)
pos = np.arange(sorted_idx.shape[0])
plt.barh(pos, feature_importances[sorted_idx], align='center', height=0.8)
plt.yticks(pos, df_year_four.columns[sorted_idx])
plt.show()
Due to privacy let me say this: The feature names on the y-axis are overlapping (there are about 30 of them). I was looking into the documentation of matplotlib in order to get an understanding of how to do this by myself, unfortunately I couldn't find anything helpful. Seems like training and testing models is easier than understanding matplotlib and creating plots :D
Thank you so much for helping out and taking the time, I appreciate it.
I see your solution, and I want to just add this link here to explain why: How to change spacing between ticks in matplotlib?
The spacing between ticklabels is exclusively determined by the space between ticks on the axes. Therefore the only way to obtain more space between given ticklabels is to make the axes larger.
The question I linked shows that by making the graph large enough, your axis labels would naturally be spaced better.
You are using np.argsort that will return a numpy array with many indices. And you are using that array as labels for your Y-Axis thus there is overlapping of labels.
My suggestion will be to use an index for sorted_idx like,
plt.yticks(pos, df_year_four.columns[sorted_idx[0]])
This will plot only for 1 label.
Got it guys!
'Geistesblitz' as we say in germany! (spiritual lightening)
See the variable feature_importances in the third top row? Add feature_importnaces[:-15]
to view only the top half of the features and loosen up the y-axis. Yes!!! This does well because there are way less important features.
My current problem is that I want to know how many likes a user receives before he/she stops opening his/her notifications.
I have tried plotting this in python using google colab. However, when using a scatter plot, no number or pattern emerges. I also tried plotting it using 2 distribution plots, with an overlap.
python code for scatter plot
plot_data = [
go.Scatter(
x=merge3['user_id'],
y=merge3['notifopentotal'],
name = 'Opened Notification')]
python code for distribution plot
enable_plotly_in_cell()
Add histogram data
x1 = merge3['totalLikes']
x2 = merge3['notifopentotal']
Group data together
hist_data = [x1, x2]
group_labels = ['totalLikes', 'notifopentotal']
Create distplot with custom bin_size
fig = ff.create_distplot(hist_data, group_labels, bin_size=10)
pyoff.iplot(fig)
The scatter plot resulted to disorganized lines. I was expecting to see a point of diversion, wherein the point is the number of likes a user receives before he/she stops opening her notifications.
The 2 distribution plots for likes and opened notifications overlapped in some areas and there was a point in their density curves that overlapped.
Is it safe to assume that this is the answer?
I am looking for a function in Gnuplot to create a so called Beeswarm dotplot. This is very popular plots used in medicine and biology. I know it can be done in Grapgpad Prism and in R but I would like to continue using Gnuplots for making graphs