logo
Tags down

shadow

Pyplot scatterplot interfering with line


By : arnavguru28
Date : October 16 2020, 08:10 PM
wish helps you So I have a list of numbers as well as the mean and standard deviation of this list. I am attempting to plot the numbers as x values and then plot the lists standard distribution on the same graph however they seem to be interfering with one another. Individually they work fine. , Your code works:
code :
import matplotlib.pyplot as plt
import scipy.stats

class1 = np.random.uniform(-2.4, -1, 100)
mean1 = class1.mean()
std1 = class1.std()

plt.scatter(class1, [0]*len(class1), marker="x", label="C1", c="black")
plt.xlabel('X')
plt.ylabel('P(X|C)')
plt.title('X vs P(X|C)')
plt.legend()
x = np.linspace(mean1 - 3*std1, mean1 + 3*std1, 100)
plt.plot(x, scipy.stats.norm.pdf(x, mean1, std1))
plt.show()


Share : facebook icon twitter icon

matplotlib.pyplot scatterplot legend from color dictionary


By : user3924582
Date : March 29 2020, 07:55 AM
Any of those help I'm trying to make a legend with my D_id_color dictionary for my scatterplot. How can I create a legend based on these values with the actual color? , One way to achieve this:
code :
D_id_color = {'A': u'orchid', 'B': u'darkcyan', 'C': u'grey', 'D': u'dodgerblue', 'E': u'turquoise', 'F': u'darkviolet'}
x_coordinates = [1,2,3,4,5,6] # Added missing datapoint
y_coordinates = [3,3,3,3,3,3] # Added missing datapoint
size_map = [50,100,200,400,800,1200] # Added missing datapoint
color_map = [color for color in D_id_color.values()[:len(x_coordinates)]]
plt.scatter(x_coordinates,y_coordinates, s = size_map, c = color_map)

# The following two lines generate custom fake lines that will be used as legend entries:
markers = [plt.Line2D([0,0],[0,0],color=color, marker='o', linestyle='') for color in D_id_color.values()]
plt.legend(markers, D_id_color.keys(), numpoints=1)

plt.show()

Animate a ScatterPlot with PyPlot


By : Dyarsa S. Pamungkas
Date : March 29 2020, 07:55 AM
This might help you As @s0upa1t comments you should have figure handle as the first argument to animation. The criptic error results from animation expecting a fig object, which has attribute canvas but instead gets scatter, a PathCollection object, which does not. As a minimal example of animation in the form you want, consider,
code :
import matplotlib.pyplot as plt 
from matplotlib.animation import FuncAnimation
import numpy as np

dt = 0.005
n=20
L = 1
particles=np.zeros(n,dtype=[("position", float , 2),
                            ("velocity", float ,2),
                            ("force", float ,2),
                            ("size", float , 1)])

particles["position"]=np.random.uniform(0,L,(n,2));
particles["velocity"]=np.zeros((n,2));
particles["size"]=0.5*np.ones(n);

fig = plt.figure(figsize=(7,7))
ax = plt.axes(xlim=(0,L),ylim=(0,L))
scatter=ax.scatter(particles["position"][:,0], particles["position"][:,1])

def update(frame_number):
    particles["force"]=np.random.uniform(-2,2.,(n,2));
    particles["velocity"] = particles["velocity"] + particles["force"]*dt
    particles["position"] = particles["position"] + particles["velocity"]*dt

    particles["position"] = particles["position"]%L
    scatter.set_offsets(particles["position"])
    return scatter, 

anim = FuncAnimation(fig, update, interval=10)
plt.show() 

Pyplot scatterplot legend not working with smaller sample sizes


By : Aayam Bhardwaj
Date : March 29 2020, 07:55 AM
To fix this issue You need to make sure not to confuse the class itself with the number you use for indexing.
To better observe what I mean, use the following dataset with your function:
code :
np.random.seed(22)
X,Y= np.meshgrid(np.arange(3,7), np.arange(4,8))
test2 = pd.DataFrame({
    'y': Y.flatten(),
    'x': X.flatten(),
    'group': np.random.randint(0,9,len(X.flatten()))
})
plot_scatter_test(test2['x'], test2['y'],test2['group'])
import numpy as np; np.random.seed(22)
import matplotlib.pyplot as plt
import pandas as pd

def plot_scatter_test(x, y, c, title="title"):
    data = pd.DataFrame({'x': x, 'y': y, 'c': c})
    classes = np.unique(c)
    print classes
    colors = plt.cm.rainbow(np.linspace(0, 1, len(classes)))
    print colors
    ax = plt.subplot(111)
    for i, clas in enumerate(classes):
        ss = data[data['c']==clas]
        plt.scatter(ss["x"],ss["y"],c=[colors[i]]*len(ss), label=clas)

    ax.legend(loc='lower left',scatterpoints=1, ncol=3, fontsize=8,  title='Legend')
    plt.show()

X,Y= np.meshgrid(np.arange(3,7), np.arange(4,8))
test2 = pd.DataFrame({
    'y': Y.flatten(),
    'x': X.flatten(),
    'group': np.random.randint(0,9,len(X.flatten()))
})
plot_scatter_test(test2['x'], test2['y'],test2['group'])

How to change the size of a pyplot scatterplot?


By : DennisW83
Date : March 29 2020, 07:55 AM
fixed the issue. Will look into that further Version 1: subplots
If you do it as subplots you can share an axis, so they will have the same ratio (scale of axes). Here an example:
code :
x=np.random.random((2,20))
>>> x[1,:]*=5
>>> x
array([[0.61385822, 0.06513556, 0.38509674, 0.88475931, 0.61135633,
        0.52850788, 0.28874746, 0.31957553, 0.56352545, 0.73032793,
        0.33251703, 0.46145744, 0.85718266, 0.9245014 , 0.82680079,
        0.64086966, 0.34268507, 0.16287025, 0.75205862, 0.83800607],
       [2.33122874, 0.85485611, 3.22991163, 3.49787662, 4.15323232,
        2.3525812 , 3.42487024, 2.88836999, 4.6458569 , 3.0970779 ,
        1.11708794, 1.43842651, 3.21363567, 0.22537731, 4.30038695,
        2.18049717, 2.41325285, 4.75072423, 1.66524457, 3.714594  ]])
>>> y=np.random.random((2,20))
>>> y
array([[0.56533792, 0.08718218, 0.44651916, 0.71774735, 0.97279402,
        0.55520593, 0.65698023, 0.74630129, 0.02921527, 0.0346008 ,
        0.16860719, 0.4033271 , 0.65322063, 0.07031113, 0.11294362,
        0.01561782, 0.46711258, 0.95043895, 0.41240197, 0.48960332],
       [0.13080883, 0.74344444, 0.42144694, 0.19517648, 0.40808507,
        0.73776604, 0.16057131, 0.78187482, 0.47684809, 0.7813126 ,
        0.02526416, 0.5067928 , 0.94726587, 0.76381176, 0.06206742,
        0.34659303, 0.28615481, 0.93999695, 0.37723651, 0.63998848]])
>>> ax=plt.subplot(121)
>>> plt.scatter(x[0,:],x[1,:])
<matplotlib.collections.PathCollection object at 0x7f84a1e72950>
>>> plt.subplot(122,sharex=ax,sharey=ax)
<matplotlib.axes._subplots.AxesSubplot object at 0x7f84a1e72f50>
>>> plt.scatter(y[0,:],y[1,:])
<matplotlib.collections.PathCollection object at 0x7f84a1dfaa50>
>>> plt.show()
plt.scatter(x[0,:],x[1,:])
<matplotlib.collections.PathCollection object at 0x7f84a0dd3ed0>
>>> xmin,xmax = plt.xlim()
>>> ymin,ymax = plt.ylim()
>>> plt.show()
>>> plt.scatter(y[0,:],y[1,:])
<matplotlib.collections.PathCollection object at 0x7f84a0d09410>
>>> plt.xlim(xmin,xmax)
(0.015514037327494477, 0.9741229215679024)
>>> plt.ylim(ymin,ymax)
(-0.00981860392769604, 4.985920150990175)
>>> plt.show()

Python Pyplot Scatterplot with USA State markers


By : Rahul Bajaj
Date : March 29 2020, 07:55 AM
hope this fix your issue I am trying to create a scatterplot using Python Pyplot. I am new to using Python and wanted to know you to include the USA state abbreviations as the markers for my scatterplot where the x and y data has states as a data field. Any ideas? , Try this piece of code
Related Posts Related Posts :
  • String Manipulation Recursive Function
  • Filter after Groupby and Sum in pandas?
  • writing a custom function Multiply the average of x,y
  • Spotify API fetch authorization code from redirect_uri
  • sklearn use RandomizedSearchCV with custom metrics and catch Exceptions
  • IndexOutOfRange error when filling a List Python
  • sns stripplot with just top n number of categories
  • Python classes keep calling eachother
  • How do I create a Dataframe_new in python from an existing Dataframe_old.
  • calculating an intercept point between a straight line and an ellipse - python
  • Integrating Tensorflow object detection with keras cnn classifier
  • How to skip comma while reading CSV file in python?
  • Stop Integrating when Output Reaches 0 in scipy.integrate.odeint
  • Changing the current graph of tf.placeholder objects in Tensorflow: Is it possible?
  • Logical error in while statement when used with or operator
  • django-rest-framework: int() argument must be a string, a bytes-like object or a number, not Deferred Attribute
  • how to remove a whitespace in a list in python?
  • How to reduce the number of row repetitions in a numpy array
  • Python: Dividing values of nested list with values with values of dictionary
  • Printing empty Pyramid
  • Python: How to save log file toSharePoint
  • Python Pandas count most frequent occurrences
  • How can I store / cache values from methods in a class for later use in other methods of the same class?
  • Sklearn: Pass class names to make_scorer
  • PyTorch - applying attention efficiently
  • How do I capitalize each parameter in a function definition using Python?
  • Regex matching of a bytes pattern gives unusual results - '.' not equivalent to [\x00-\xff]
  • I need help converting this REST API Curl command to Python requests
  • How do you make a variable comparison to decide a better score in a dice game?
  • How do I run sumo-gui on instant-veins-4.7.1-i1.ova
  • Deal with NAN values when creating models with python
  • Python requests: having a space in header for posting
  • Adding a column to a pandas dataframe based on cell values
  • Get mongod rs.status() results from a python script
  • ImportError: C extension: No module named 'parsing' not built
  • python pandas update column values related to previous updated row during iteration over it
  • 3 nested loops: Optimizing a simple simulation for speed
  • Assign subset of values to pandas dataframe with MultiIndex
  • How to group two sets of buttons on each top corner of the screen using Tkinter?
  • django login using class based for custom user
  • MRJob sort reducer output
  • Python Pandas Counts using rolling time window
  • Getting or editing a string from a column in a csv file with pandas
  • Python - Delete row in matrix/array if row contains
  • Using dicom Images with OpenCV in Python
  • Odoo ghost record
  • Creating and assigning multiple variables in a tkinter application
  • Graph dictionary
  • No changes to original dataframe after applying loop
  • AUC of Random forest model is lower after tuning parameters using hypergrid search and CV with 10 folds
  • Python: Reading multiple CSV files, and assigning each to a different variable
  • How to identify empty rectangle using OpenCV
  • How to iterate multilevel dataframe in python
  • How to limit the contour plot with a line plot?
  • Why subclassing a str or int behaves differently from subclising a list or dict?
  • Python decode with translation table
  • i need to click unordered links in the below URL using selenium, python
  • How to join pandas dataframe with itself?
  • How to apply a color cast to a video frame in OpenCV Python?
  • Is there any existing library for median filtering with kernel size greater then 5 using OpenCL acceleration in python?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org