How to customize the form of polynomial formula in more detail than just setting the number of dimensions in react-google-charts - polynomials

Background
I am coding an frontend page in typescript with react-google-charts to scatter plots and draw a 3-dimensional polynomial trendline based on the plots.
I am required to draw the trendline whose formula should not be like "ax^3 + bx^2 + cx + d" but just "ax^3".
Looking over the official documents, I found I can define the number of dimension by "degree" key in option parameter:
options = {
....
trendlines: {
0: {
type: "polynomial",
degree: 3,
visibleInLegend: false,
pointSize: 20, // Set the size of the trendline dots.
opacity: 1,
},
....
}
However, I cannot find the way to customize the terms of the polynomial.
Questions
How to customize the terms of the polynomial trendline?
If it is impossible, what could be the alternatives? (I guess I would have to manually implement a least squares method for calculate the coefficients from the scatter plots.
I looked over the following websites, but could not find the parameters customizing the terms of polynomial trendline formulas.
https://developers.google.com/chart/interactive/docs/gallery/trendlines#polynomial-trendlines
https://www.react-google-charts.com/components/chart

Related

How to create a serial from column values to calculate the slope in Google Sheets?

I have the following spreadsheet:
https://docs.google.com/spreadsheets/d/1Ib2Do3htfRg3NAuI-HyRA3MBM1XwUviFcAxlvF7q1J0/edit?usp=sharing
I have created 2 sparklines, 1 works, 1 doesn't. The one that does not work references the second column as the x-axis to calculate the slope. The slope is needed to give the graph some nice trending color.
My question is, how can I convert the second column into a serial [1, 2, 3, 4, 5]? So that when it is put as the x-axis, the slope would be calculated correctly. Of course, this conversion needs to happen within the formula itself. Thanks for any help.
try:
=ARRAYFORMULA(SPARKLINE(C2:C, {
"charttype", "line";
"color", IF(SLOPE(C2:C, ROW(B2:B)-1)>0, "lime", "red");
"linewidth", 2}))

Python Matplotlib creating a custom colour scale

I have created a map of precipitation levels in a region based on precipitation data from NetCDF files. I would like to add a custom scale such that if precipitation is less than 800mm it would be one colour, 800-1000mm another, etc. Similar to the map found here: http://www.metmalawi.com/climate/climate.php
At the moment I am using a gradient scale but it isn't showing the detail I need. This is the code for the plot at the moment (where 'Average' is my data that I have already formatted).
#load color palette
colourA = mpl_cm.get_cmap('BuPu')
#plot map with physical features
ax = plt.axes(projection=cartopy.crs.PlateCarree())
ax.add_feature(cartopy.feature.COASTLINE)
ax.add_feature(cartopy.feature.BORDERS)
ax.add_feature(cartopy.feature.LAKES, alpha=0.5)
ax.add_feature(cartopy.feature.RIVERS)
#set map boundary
ax.set_extent([32.5, 36., -9, -17])
#set axis tick marks
ax.set_xticks([33, 34, 35])
ax.set_yticks([-10, -12, -14, -16])
lon_formatter = LongitudeFormatter(zero_direction_label=True)
lat_formatter = LatitudeFormatter()
ax.xaxis.set_major_formatter(lon_formatter)
ax.yaxis.set_major_formatter(lat_formatter)
#plot data and set colour range
plot = iplt.contourf(Average, cmap=colourA, levels=np.arange(0,15500,500), extend='both')
#add colour bar index and a label
plt.colorbar(plot, label='mm per year')
#give map a title
plt.title('Pr 1990-2008 - Average_ERAINT ', fontsize=10)
#save the image of the graph and include full legend
plt.savefig('ERAINT_Average_Pr_MAP_Annual', bbox_inches='tight')
plt.show()
Anyone know how I can do this?
Thank you!
This is a matplotlib question disguised as an Iris question as the issue has appeared via Iris plotting routines, but to answer this we need only a couple of matplotlib commands. As such, I'm basing this answer on this matplotlib gallery example. These are levels (containing values for the upper bound of each contour) and colors (specifying the colours to shade each contour). It's best if there are the same number of levels and colours.
To demonstrate this, I put the following example together. Given that there's no sample data provided, I made my own trigonometric data. The levels are based on the trigonometric data values, so do not reflect the levels required in the question, but could be changed to the original levels. The colours used are the hex values of the levels specified by image in the link in the question.
The code:
import matplotlib.pyplot as plt
import numpy as np
x = np.arange(-25, 25)
y = np.arange(-20, 20)
x2d, y2d = np.meshgrid(x, y)
vals = (3 * np.cos(x2d)) + (2 * np.sin(y2d))
colours = ['#bf8046', '#df9f24', '#e0de30', '#c1de2d', '#1ebf82',
'#23de27', '#1dbe20', '#11807f', '#24607f', '#22427e']
levels = range(-5, 6)
plt.contourf(vals, levels=levels, colors=colours)
plt.colorbar()
plt.show()
The produced image:
Colours could also be selected from a colormap (one way of doing this is shown in this StackOverflow answer). There are also other ways, including in the matplotlib gallery example linked above. Given, though, that the sample map linked in the question had specific colours I chose to use those colours directly.

Editing Radar Charts for Labeling and Axis Limits

I have been playing with the radar chart concept for visualizing percentage-based metrics. I have followed sample code but am having trouble with a few items. Can anyone help me with changing the labels from the default degree values to something else? I also want to set the x-axis minimum to 0.9, but struggled a bit.
Any help or resources are helpful. If there is a more efficient way to solve them, I am open to starting over again.
import numpy as np
import matplotlib.pyplot as plt
availability_array = np.array([.95, .9, .99, .97, 1]) #sample inverter uptime availability numbers using site with 5 inverters
# Compute pie slices
theta = np.linspace(0.0, 2 * np.pi, len(availability_array), endpoint=False)
values = availability_array #values that are graphed
width = 1 #increase/decrease width of each bar
ax = plt.subplot(111, projection='polar') #.set_xticklabels(['N', '', 'W', '', 'S', '', 'E', '']) #111 means 1x1 grid subplot starting in cell 1
bars = ax.bar(theta, values, width=width, bottom=0.0)
# Coloring
for r, bar in zip(values, bars):
bar.set_facecolor(plt.cm.viridis(r / 1))
bar.set_alpha(0.4) #transparency of the bars
plt.show()
As you've already shown in your comments, labels around the circle are xticklabels and labels along the radius are yticklabels, i.e. y-axis is along the radius. Therefore, I think you meant to "set the y-axis minimum to 0.9".
As you would do with regular plot, you can use set_xticks in combine with set_xticklabels to change "the labels from the default degree values to something else". For example:
ax.set_xticks([np.pi/4, np.pi*3/4])
ax.set_xticklabels(['NE', 'NW'])
To "set the y-axis minimum to 0.9", you can use set_ylim like this:
ax.set_ylim(0.9, 1)

Jaccard similarity in python

I am trying to find the jaccard similarity between two documents. However, i am having hard time to understand how the function sklearn.metrics.jaccard_similarity_score() works behind the scene.As per my understanding the Jaccard's sim = intersection of the terms in docs/ union of the terms in docs.
Consider below example:
My DTM for the two documents is:
array([[1, 1, 1, 1, 2, 0, 1, 0],
[2, 1, 1, 0, 1, 1, 0, 1]], dtype=int64)
above func. give me the jaccard sim score
print(sklearn.metrics.jaccard_similarity_score(tf_matrix[0,:],tf_matrix[1,:]))
0.25
I am trying to find the score on my own as :
intersection of terms in both the docs = 4
total terms in doc 1 = 6
total terms in doc 2 = 6
Jaccard = 4/(6+6-4)= .5
Can someone please help me understand if there is something obvious i am missing here.
As stated here:
In binary and multiclass classification, the Jaccard similarity coefficient score is equal to the classification accuracy.
Therefore in your example it is calculating the proportion of matching elements. That's why you're getting 0.25 as the result.
According to me
intersection of terms in both the docs = 2.
peek to peek intersection according to their respective index. As we need to predict correct value for our model.
Normal Intersection = 4. Leaving the order of index.
# so,
jaccard_score = 2/(6+6-4) = 0.25

Is there any way to add gridlines to a gRaphael line chart?

I have a line chart that I've created with gRaphael. It has axes and tick marks, but I'd like to have grid lines. Is there built-in way to achieve this or an add on library that can help me?
gRaphael does not have a built-in way to add grid lines, but it is pretty easy to draw them, either by editing the source code or manipulating your graph object after you create it.
I had found an extension called RaphAlytics and used its drawGrid() function in cases where I needed a bounding box with a grid.
You can adapt this function for any gRaphael graph as needed to draw gridlines. On a line chart, I needed to draw horizontal gridlines that were aligned with the left axis marks on a line chart, so I used the function as an example like this:
// Draw horizontal gridlines
for (var i = 0; i < g.axis[1].text.items.length; i++) {
r.path(['M', x, g.axis[1].text.items[i].attrs.y, 'H', w + x]).attr({
stroke : '#EEE'
}).toBack();
}
Here's a working fiddle to illustrate that example: http://jsfiddle.net/KM3BB/1/
I tried doing this yesterday. Short answer: gRaphaël can't do this for you with any linechart options nor axis options, you have to do-it-yourself with Raphaël.
Something like:
var r = Raphael("holder"), txtattr = { font: "12px sans-serif" };
r.path('M 15 200.5 L 310 200.5 M 15 180.5 L 310 200.5');
r.linechart(10, 10, 300, 220, x, [y, y2, y3]);
This means under my linechart draw a path which starts from 15,200.5 and draws a straight line to 310,200.5 moves to 15,180.5 and draws a line to 310,180.5. Don't ask me why but the .5 is important for getting the stroke to actually be 1px wide and solid black. Otherwise it seems to get aliased to 2px wide at 50% opacity. You have to calculate the exact placement in regards to your linechart yourself.
You can also play with the path function in the playground by changing r to paper.
You might also consider looking at Google Chart Tools if your looking for things like defining the exact range of the axis (as opposed to just the min and max of the input).