Just getting into matplot lib and running into odd problem - I'm trying to plot 10 items, and use their names on the x-axis. I followed this suggestion and it worked great, except that my label names are long and they were all scrunched up. So I found that you can rotate labels, and got the following:
plt.plot([x for x in range(len(df.columns))], df[df.columns[0]], 'ro',)
plt.xticks(range(10), df.columns, rotation=45)
The labels all seem to be off by a tick ("Arthrobacter" should be aligned with 0). So I thought my indexing was wrong, and tried a bunch of other crap to fix it, but it turns out it's just odd (at least to me) behavior of the rotation. If I do rotation='vertical', I get what I want:
I see now that the center of the labels are clearly aligned with the ticks, but I expected that they'd terminate on the ticks. Like this (done in photoshop):
Is there a way to get this done automatically?
The labels are not "off", labels are actually placed via their "center". In your second image, the corresponding tick is above the center of the label, not above its endpoint. You can change that by adding ha='right' which modifies the horizontal alignement of the label.
plt.plot([x for x in range(len(df.columns))], df[df.columns[0]], 'ro',)
plt.xticks(range(10), df.columns, rotation=45, ha='right')
See the comparison below :
1)
plt.plot(np.arange(4), np.arange(4))
plt.xticks(np.arange(4), ['veryverylongname']*4, rotation=45)
plt.tight_layout()
2)
plt.plot(np.arange(4), np.arange(4))
plt.xticks(np.arange(4), ['veryverylongname']*4, rotation=45, ha='right')
plt.tight_layout()
Related
I have a RRD database with data:
"DS:pkts_transmitted:GAUGE:120:0:U",
"DS:pkts_received:GAUGE:120:0:U",
"DS:pkts_lost:GAUGE:120:0:U",
"DS:rtt_min:GAUGE:120:0:U",
"DS:rtt_avg:GAUGE:120:0:U",
"DS:rtt_max:GAUGE:120:0:U",
And I want that the Avg line change colour if I lose any package.
For example, if I lose 5 packets make the line blue, if I lose 10 make it red.
I see people doing it but I read the documentation and I can't find how to do this.
The way to do this is to actually have multiple lines defined (one of each colour) and hide the ones you don't want to see at any time, using calculations.
For example, say we have an RRD with two DSs:
DS:x:GAUGE:60:0:U
DS:y:GAUGE:60:0:1
Now, we want to show the line for x in red if y is 0, and blue if it is 1. To do this, we create two calculated values, x1 and x2.
CDEF:x1=y,0,EQ,x,UNKN,IF
CDEF:x2=y,1,EQ,x,UNKN,IF
Thus, x1 is active if y=0 and x2 if y=1. Yes, this could be simplified, but I'm showing it like this for the example.
Now, we can make lines using these:
LINE:x1#ff0000:MyLine
LINE:x2#0000ff
Note that the second line doesn't need a legend. Now, the line will appear to change colour depending on the value of the y metric, since at any time the other line will be UNKN and therefore not displayed.
You can extend this, of course, to have multiple colours and more complex thresholds.
I want to make a figure that marker's size depend on the size of the figure. That way, using square marker size, no matter what resolution or figure size you choose, all the markers will touch each other, masking the backgroud without overlapping. Here is where I am at:
The marker size is specified in pt^2, with 1pt=1/72inch, the resolution in Pixel Per Inches, and the figure size in pixels (also the proportion that main subplot represent out of the main figure size : 0.8). So, if my graph's limits are lim_min and lim_max, I should by able to get the corresponding marker size using :
marker_size=((fig_size*0.8*72/Resolution)/(lim_max-lim_min))**2
because (fig_size*0.8*72/Resolution) is the size of the figure in points, and (lim_max-lim_min) the number of marker I want to fill a line.
And that should do the trick !... Well it doesn't... At all... The marker are so small they are invisible without a zoom. And I don't get why.
I understand this my not be the best way, and the way you would do it, but I see no reason why it wouldn't work, so I want to understand where I am wrong.
PS : both my main figure and my subplot are squares
Edit :
Okay so I found the reason of the problem, not the solution. The problem in the confusion between ppi and dpi. Matplotlib set the resolution in dpi, which is defined as a unit specific to scanner or printer depending on the model (?!?).
Needless to say I am extremely confused on the actual meaning of the resolution in matplotlib. It simply makes absolutely no sens to me. Please someone help. How do i convert this to a meaningful unit ? It seems that matplotlib website is completely silent on the matter.
If you specify the figure size in inches and matplotlib uses a resolution of 72 points per inch (ppi), then for a given number of markers the width of each marker should be size_in_inches * points_per_inch / number_of_markers points (assuming for now that the subplot uses the entire figure)? As I see it, dpi is only used to display or save the figure in a size of size_in_inches * dpi pixels.
If I understand your goal correctly, the code below should reproduce the required behavior:
# Figure settings
fig_size_inch = 3
fig_ppi = 72
margin = 0.12
subplot_fraction = 1 - 2*margin
# Plot settings
lim_max = 10
lim_min = 2
n_markers = lim_max-lim_min
# Centers of each marker
xy = np.arange(lim_min+0.5, lim_max, 1)
# Size of the marker, in points^2
marker_size = (subplot_fraction * fig_size_inch * fig_ppi / n_markers)**2
fig = pl.figure(figsize=(fig_size_inch, fig_size_inch))
fig.subplots_adjust(margin, margin, 1-margin, 1-margin, 0, 0)
# Create n_markers^2 colors
cc = pl.cm.Paired(np.linspace(0,1,n_markers*n_markers))
# Plot each marker (I could/should have left out the loops...)
for i in range(n_markers):
for j in range(n_markers):
ij=i+j*n_markers
pl.scatter(xy[i], xy[j], s=marker_size, marker='s', color=cc[ij])
pl.xlim(lim_min, lim_max)
pl.ylim(lim_min, lim_max)
This is more or less the same as you wrote (in the calculation of marker_size), except the division by Resolution has been left out.
Result:
Or when settings fig_ppi incorrectly to 60:
I have the following array that I wish to turn into a Google line chart:
array = [
['Period 12', '165', '183'],
['Period 11', '145', '133'],
['Period 10', '125', '143'],
...
]
The 1st column represents the label on the x-axis, the 2nd is the value for the current period and the 3rd is the value for the last period.
I am using formatters for the number values so that they show a prefix ($ or £).
I push each row into Google's TableData, I set the current trend line to be bright blue and the previous one a faded blue. This is the result:
As you can see, the previous trend line is drawn 'over' the current one. I was wondering is it possible to 'flip' the order in which they're drawn?
I've tried pushing the values of the 3rd column first and then the 2nd column AND flipping the colors of the trend lines. But in that case the popups on the points show the wrong periods (light blue becomes current period and light blue - previous period) like so:
I've check and double checked this approach, but it doesn't seem to work.
Any help is appreciated!
PS: Sorry for the links, reputation doesn't allow posting images directly.
Don't know if you solved the problem, but I had a similar problem with the ordering. In my case having a pointSize added to the options was the problem, eventho I changed the order of the columns. Removing the pointSize solved the problem.
I want to merge 2 images. How can i remove the same area between 2 images?
Can you tell me an algorithm to solve this problem. Thanks.
Two image are screenshoot image. They have the same width and image 1 always above image 2.
When two images have the same width and there is no X-offset at the left side this shouldn't be too difficult.
You should create two vectors of integer and store the CRC of each pixel row in the corresponding vector element. After doing this for both pictures you find the CRC of the first line of the lower image in the first vector. This is the offset in the upper picture. Then you check that all following CRCs from both pictures are identical. If not, you have to look up the next occurrence of the initial CRC in the upper image again.
After checking that the CRCs between both pictures are identical when you apply the offset you can use the bitblit function of your graphics format and build the composite picture.
I haven't come across something similar before but I think the following might work:
Convert both to grey-scale.
Enhance the contrast, the grey box might become white for example and the text would become more black. (This is just to increase the confidence in the next step)
Apply some threshold, converting the pictures to black and white.
afterwards, you could find the similar areas (and thus the offset of overlap) with a good degree of confidence. To find the similar parts, you could harper's method (which is good but I don't know how reliable it would be without the said filtering), or you could apply some DSP operation(s) like convolution.
Hope that helps.
If your images are same width and image 1 is always on top. I don't see how that hard could it be..
Just store the bytes of the last line of image 1.
from the first line to the last of the image 2, make this test :
If the current line of image 2 is not equal to the last line of image 1 -> continue
else -> break the loop
you have to define a new byte container for your new image :
Just store all the lines of image 1 + all the lines of image 2 that start at (the found line + 1).
What would make you sweat here is finding the libraries to manipulate all these data structures. But after a few linkage and documentation digging, you should be able to easily implement that.
I'm trying to plot some data using qt 4.8 and qwt 6, but my curves doesn't scales over plot (1).
This is how I attach curves to plot:
curves[moduleIndex][channelIndex]->setSamples(samples, data);
curves[moduleIndex][channelIndex]->attach(plots[moduleIndex][channelIndex]);
samples and data is QVectors and samples.size() is equal to data.size()
plots[moduleIndex][channelIndex]->axisAutoScale(QwtPlot::xBottom) returns true, so autoScale is enabled.
So am I missing something?
UPDATE: I thought that the problem occures because disabled axis
plots[i][j]->enableAxis(QwtPlot::yLeft, false);
plots[i][j]->enableAxis(QwtPlot::xBottom, false);
But I've commented it out and it didn't help.
I believe 'autoscale' is alreadyworking. But to make axis look nice, it takes a rounded number for maximum which is causing a gap at the end. Scales of QwtPlot are managed by QwtScaleEngine. You can get a pointer to default scaleEngine your plot using with QwtPlot::axisScaleEngine(...). Setting Floating attribute to true will remove this gap and will fit your data to boundaries. See docs: http://qwt.sourceforge.net/class_qwt_scale_engine.html
Ex:
plot.axisScaleEngine(QwtPlot::xBottom)->setAttribute(QwtScaleEngine::Floating,true);
When setting QwtScaleEngine::Floating + QwtPlotLayout::setAlignCanvasToScales( true ) the canvas should be perfectly aligned to the boundaries of your curve.