Tag Info

Hot answers tagged matplotlib

13

I'll just be cheeky and post a slightly modified version of my SO answer here. So first things first, you want to get rid of the loops. They are slow to execute. The first loop: for x in range(rows): for y in range(cols): if Z[x][y] == 1: if (N[x][y] < 2) or (N[x][y] > 3): Z[x][y] = 0 ...

11

matplotlib adding stuff to the current figure is because you are not using the OO-interface. It is slightly clunkier, but allows way more freedom In my view, you are mixing several things up. I would seperate the generation of the timings, the aggregation of these results and the plotting. In this way, if you want to change to another plotting library (...

10

I've never used numpy or matplotlib, so I can only speak to issues of style. You're allowing for far too much nesting here. Your code consists of a giant, dense, deeply nested chunk. As a result, the eyes have very few good landmarks to rest on; making your code hard to read. Put your existing function definitions at the very top level outside of any ...

8

You're not really using numpy at the moment. If we use the simple 'translation table' below, your code would work if you just replaced the NumPy function with the Python equivalent: np.arange -> range, assuming your domain is just integers, np.fabs -> abs, np.cos -> math.cos, and, np.pi -> math.pi. Instead you want to take advantage of NumPy. Take ...

8

First, a style comment. On the internet, especially in programming, and in particular on this website, English is the lingua franca. So you should avoid mixing other languages and English. This way your code is the most transferable, re-usable and readable. Second, a comment on the algorithm itself. Your algorithm (and this includes any changes I make to it ...

8

I'm going to put this code into an editor, "proofread" it from top to bottom, give notes as I go, and then paste the final result to show the effect of the edits. Code editors don't usually wrap lines since linebreaks mean things in code. Consequently, most coding style guidelines suggest limiting your column width so the reader doesn't need to scroll ...

7

The biggest issue I see is code organization. There are two large tasks: Numerical Simulation Data Visualization They are mixed together in ways that create arbitrary dependencies and make extending and maintaining the code difficult. Names Assigning meaningful names to numbers will improve readability and reduce comments: right = 1 left = 2 up = 3 ...

7

This is my first Python script using argparse instead of sys for argument handling. I'm especially interested in whether the way I implemented it is up to par. You nailed it :-) Under the argument parsing I have a couple of BOLD_SNAKE_CASE variables which are pseudo constants. There's probably a better way to do this. That's the common practice in ...

7

Well, unfortunately you can't get any better than this (as far as I have read). And why would you use an iterator in this case ? I'd however change a bit of the structure of your code, which allows one to easily change the code if there's any need. I didn't changed too many things, just separated the logic into three different functions and added a for loop ...

7

You need not declare # -*- coding: utf-8 -*- in Python 3: UTF-8 is the default. Writing I = np.logspace(…) inside your curve_equation function is bad practice, because it hard-codes certain x-values for your plot. In fact, your plot is wrong, because the calculations are for $I_s$ values ranging from 102 A to 105 A (due to the inner I = np.logspace(np....

7

Nice. Here are some observations: consider using an IntEnum: This helps remove "magic" numbers from the source code. (A year from now, will you remember that if self.selected_type == 3 is a check to see if the mode is 'File'?) from enum import auto, IntEnum class SoundType(IntEnum): NOTE = auto() DESIGN = auto() FILE = auto() Then later ...

6

Style Your docstring at the top of the seq function should be moved underneath the function signature, like this: def seq(start, end, step): """Function to iterate with decimal step size""" ... The variable map, should be written like this, to improve clarity and readability: map = Basemap( projection="merc", resolution = 'h', ...

6

DISCLAIMER: I don't know cython and have never used it, so if any of my advice doesn't apply because of cython limitations, feel free to disregard it. Counting neighbors in a game board is very easy to do via convolution with the proper kernel. Below, I used SciPy's convolve function, not the much faster fftconvolve, because the latter only works on floats ...

6

This code is really nice, and the output is very good looking! I do have a few nitpicky things that I want to cover. Why are you storing the usage in a variable named usage? This should be in the file's main docstring. You don't need to print usage under if __name__ == "__main__":. Is # encoding: utf=8 really needed? It doesn't seem like you're using any ...

6

First off, this: Q = 1.0 ; T = 1.0 Should be expanded to this: Q = 1.0 T = 1.0 And, if Q and T aren't constants, they should be renamed to q and t. Secondly, you're missing whitespace in lots of places. For example, this: def v(self,i,j,k): Should be, again, expanded to this: def v(self, i, j, k): You should also have whitespace between mathematical ...

6

I want to start this review by explicitly saying that I don't have a deep knowledge when it comes to matplotlib but I'll give it a try anyway Have in mind that I just reviewed the code as is, keeping the same logic / functionality it has at the moment. Unused imports Don't import modules you're not using (decimal, pandas, numpy). Imports grouping From ...

6

coding style Your code is almost pep-8 compliant. There are a few spaces missing after comma's, but all in all this is not too bad. I myself use black to take care of this formatting for me. some of the variables names can be clearer. What does nc1 mean for example magic numbers The number 3, 2 and 6 are the number of rows and columns on the grid. Better ...

5

Using % for string formatting is deprecated, you should be using str.format instead. The str.format methods also allows you to do some cool things as well. Here's an example of it in action: # No positional or named arguments print "{} {}".format("Hello", "world") # Positional arguments (*args) print "{1} {0}".format("world", "Hello") # Named arguments (**...

5

Let's start with the obvious remarks about whitespace: Whitespace is important in Python. You got trailing whitespaces all over the place and you use an indentation of 2 spaces where 4 is prescribed by the official PEP8 Style Guide. When talking about sticking to best practices in Python, starting with PEP8 is a good idea. There's a lot more violations ...

5

Superficial issues """Function to iterate…""" is a docstring, which belongs inside the function definition, not before it. """Divide global area into grid cells""" should be written as a comment (# Divide global area into grid cells). The way you formatted map = Basemap(…) makes it hard to see that it's one statement over five lines. The four ...

5

Let us start with some code review, before improving the performance, and finish off with a comparision against the original code. Code review As a gesture to us reviewing your code, it would have been nice to know which modules where external to a default installation, as I had to plunder a little to install the astropy and jplephem module. However I got ...

5

First of all some style comments: Please use spaces after commas and around operators – It is hard to read your sequence of values for the X and y lists when they are all compressed. And the same applies for the ([2,7]) when setting limits. It reads a lot better with [3, 3.2, 3.5, ..., 5.8, 5.9, 5] and ([2, 7]) Choose better names for variables – Why have ...

5

Compute legendre(n) once per loop iteration instead of twice. Use np.hypot instead of np.sqrt(x**2 + z**2). Don't use phivec, just pass the arrays X and Y directly to phi, which is already almost vectorized. The only change that's needed is to use np.minimum and np.maximum instead of min and max respectively. Revised code: def phi(x, z, nlimit=35): r = ...

5

Here's my reworking of the calculation functions. Graphs look similar (didn't check details) when using the arange version of equidistant, but I think the linspace version is more balanced. The main thing when trying to use numpy is keeping track of dimensions. In this case points is an array of 8-20 values, x an array of 2001. def equidistant_points(...

5

Usually, when using for loops and numpy together, you’re probably doing it wrong. Some things you could replace in your code: Use np.arange(256) instead of np.zeros + for i in range(256); Use slicing instead of manually extracting values out of an array; Use comparisons and .sum() instead of manually counting the number of pixels of a certain color ...

5

Your function proc can be greatly reduced by using the fact that numpy functions are vectorized and most of them take the axis to act upon as an argument. This is certainly true for numpy.median and numpy.percentile. import numpy as np def proc(data): return (np.median(data, axis=0), np.percentile(data, 25, axis=0), np....

5

Your directions dictionary is only used by get_direction; why not put it inside the function rather than have it as a global? I'd maybe even put the dict inside get_chance_of_positions() and drop the get_direction() function entirely; it's short, only used once and doesn't require a docstring (its obvious how it works). Put dirs straight into the line as ...

5

Shebang #!/opt/anaconda3/bin/python This is suspicious. Usually you should just #!/usr/bin/env python and make sure that your environment uses the correct Python. Among other things, it'll make it easier for you to switch to system Python if you need it. Enums RABBIT = 0 FOX = 1 It's good that you're assigning symbols for these values, but you should ...

4

Why did you write your own functions for mean and weighted_median? It looks like you are doing fairly standard things with them, so I would use implementations from numpy or scipy instead. (And calling the median of a vector a times w a "weighted median" of vector a makes some sense but it is really just the regular vanilla median of a*w.) Your Game class ...

4

Try using matplotlib's LineCollection class. Here's an example. In your case, you might do: from matplotlib import pyplot as plt from matplotlib.collections import LineCollection ax = plt.gca() pts = myPath.reshape((-1,2)) # make a matrix of (x,y) pairs edges = LineCollection(pts) ax.add_collection(edges) plt.show()

Only top voted, non community-wiki answers of a minimum length are eligible