Title Loop within For Loop - for-loop

I need to loop through the titles in the list and I cannot seem to do so without printing the entire list every time or looping through the graphs multiple times. Thanks in advance!
title = ["West", "Plains", "Midwest", "Southeast", "Northeast"]
State_list = [West_df,Plains_df,Midwest_df,Southeast_df,Northeast_df]
title = ["West", "Plains", "Midwest", "Southeast", "Northeast"]
State_list = [West_df,Plains_df,Midwest_df,Southeast_df,Northeast_df]
for index in range(len(State_list)):
#Plot bar chart with county and population
df_pivot = pd.pivot_table(State_list[index],values="Population",index="County",columns="State")
# Plot a bar chart using the DF
ax = df_pivot.plot(kind="bar")
fig = ax.get_figure()
mplcursors.cursor(fig)
# Change the plot dimensions (width, height)
fig.set_size_inches(15, 6)
# Change the axes labels
ax.set_xlabel("County")
ax.set_ylabel("Population")
plt.title(f"Region: {title} | Population Recorded in each County")
#Plot scatter plot with deaths per capita,
plt.figure(figsize=(10,8))
plt.xlabel("Cases of Covid")
plt.ylabel("Deaths per Capita")
(slope, intercept, rvalue, pvalue, stderr) = linregress(State_list[index]["Cases"], State_list[index]["Deaths per Capita"])
regress_values = State_list[index]["Cases"] * slope + intercept
line_eq = "y = " + str(round(slope,8)) + "x + " + str(round(intercept,5))
Scatter2 = plt.scatter(State_list[index]["Cases"], State_list[index]["Deaths per Capita"],s=State_list[index]["Heart Disease"]*.3,
c=State_list[index].State.astype('category').cat.codes)
plt.plot(State_list[index]["Cases"],regress_values,color = "purple")
plt.annotate(line_eq,(10000,.007),fontsize=15,color = "purple")
plt.annotate(f"The r-squared is: {rvalue**2}",(10000,.0067),fontsize=10,color = "purple")
plt.title(f"Region: {title} | Deaths per Capita recorded by County in regards to Heart Disease")
#Hover Event
mplcursors.cursor(Scatter2, hover=True)
plt.legend(loc = "upper right",ncol= 2, handles=Scatter2.legend_elements()[0],
labels=State_list[index],
title="State")

Related

How to extract pixel value from geometry points in shp format (2500 points) starting from an Image Collection resempled

I'm trying to extract the value of each single band of Sentinel-2 after resampling the bands from 10 meters to 30 meters using the resolution of the Landsat-8 (I didn't know how to do this in another way)
This is the code using band 4 as an example. When I try to export the values ​​in a table the running time is infinite and I was not able to extract even the value for a single point.
N.B. my area is very large, it corresponds to all of southern europe
thank you !
function maskS2clouds(image) {
var qa = image.select('QA60');
var cloudBitMask = 1 << 10;
var cirrusBitMask = 1 << 11;
var mask = qa.bitwiseAnd(cloudBitMask).eq(0).and(qa.bitwiseAnd(cirrusBitMask).eq(0));
return image.updateMask(mask).divide(10000).select("B.*").copyProperties(image, ["system:time_start"]);
}
var start = '2012-01-01';
var end = '2022-12-31';
var cld_max = 30;
var s2 = ee.ImageCollection("COPERNICUS/S2_SR_HARMONIZED")
.filterBounds(Eur)
.filterDate(start,end)
.filter(ee.Filter.lt('CLOUDY_PIXEL_PERCENTAGE',60))
.map(maskS2clouds);
var land8 = ee.ImageCollection('LANDSAT/LC08/C01/T1_SR').filterBounds(Eur)
var b4 = land8.select('B4').filterBounds(Eur); // 30-m resolution
var b4s = s2.select('B4').filterBounds(Eur); // 10-m resolution
var proj_10m = b4.first()
.projection();
function resample(image) {
var b4s = image.select('B4');
var b4s_res = b4s.resample('bilinear').reproject(proj_10m);
return b4s_res;
}
var b4s_res =b4s.map(resample).filterBounds(Eur);
//original code
var pts = b4s_res.map(function(img) {
var obs = img.reduceRegion(
{geometry: points , reducer: ee.Reducer.median(), scale: 80});
return img.set('B4', obs.get('B4'));
});
Export.table.toDrive({
collection: pts,
description: 'table_csv',
folder: 'earth_engine_demos',
fileFormat: 'CSV'
});
//test with geometry composed of two single points
var pts2 = b4s_res.map(function(img) {
var obs2 = img.reduceRegion(
{geometry: geometry , reducer: ee.Reducer.median(), scale: 80});
return img.set('B4', obs2.get('B4'));
});
Export.table.toDrive({
collection: pts2,
description:'prova_csv',
folder: 'earth_engine_demos',
fileFormat: 'CSV'
});
Is it possible to find a faster way to extract the value of the points (2500 random points) in the table? Do you also know another way to apply a resampling on all bands simultaneously and extract the corresponding value of each point for each single band?

dc.js Adding count to the xAxis label

This is related to the dc.js boxPlot example. Is there an easy way to add the number of data values to each xAxis label?
exp-1 [10]
I know I can configure the xAxis label by:
chart.xAxis().tickFormat(function(k) {return k + ' []';});
But I only have access to the key and not the value count.
I would do this by keeping a map from keys to counts, refreshing it before the chart is rendered or redrawn:
var counts = {};
function get_counts() {
speedArrayGroup.all().forEach(function(kv) {
counts[kv.key] = kv.value.length;
});
}
chart.on('preRender', get_counts)
.on('preRedraw', get_counts);
Now that we're sure counts is initialized whenever the axis is drawn, we can use it in the tickFormat:
chart.xAxis().tickFormat(function(k) {return k + ' [' + counts[k] + ']';});
Not so interesting with the standard example, but it works:

Seaborn despine() brings back the ytick labels

Here is a code snippet
tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col = 'time')
g = g.map(plt.hist, "tip")
with the following output
I want to introduce despine offset to these plots while keeping the rest unchanged. Therefore, I inserted the despine function in the existing code:
tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col = 'time')
g.despine(offset=10)
g = g.map(plt.hist, "tip")
which results in the following plots
As a result, the offset is applied to the axes. However, the ytick labels on the right plot are back, which I don't want.
Could anyone help me on this?
To remove the yaxis tick labels, you can use the code below:
The libs:
import seaborn as sns
sns.set_style('ticks')
The adjusted code:
tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col = 'time')
g.despine(offset=10)
g = g.map(plt.hist, "tip")
# IMPORTANT: I assume that you use colwrap=None in FacetGrid constructor
# loop over the non-left axes:
for ax in g.axes[:, 1:].flat:
# get the yticklabels from the axis and set visibility to False
for label in ax.get_yticklabels():
label.set_visible(False)
ax.yaxis.offsetText.set_visible(False)
A bit more general, image you now have a 2x2 FacetGrid, you want to despine with an offset, but the x- and yticklabels return:
Remove them all using this code:
tips = sns.load_dataset("tips")
g = sns.FacetGrid(tips, col = 'time', row='sex')
g.despine(offset=10)
g = g.map(plt.hist, "tip")
# IMPORTANT: I assume that you use colwrap=None in FacetGrid constructor
# loop over the non-left axes:
for ax in g.axes[:, 1:].flat:
# get the yticklabels from the axis and set visibility to False
for label in ax.get_yticklabels():
label.set_visible(False)
ax.yaxis.offsetText.set_visible(False)
# loop over the top axes:
for ax in g.axes[:-1, :].flat:
# get the xticklabels from the axis and set visibility to False
for label in ax.get_xticklabels():
label.set_visible(False)
ax.xaxis.offsetText.set_visible(False)
UPDATE:
for completeness, mwaskom (ref to github issue) gave an explanation why this issue is occuring:
So this happens because matplotlib calls axis.reset_ticks() internally when moving the spine. Otherwise, the spine gets moved but the ticks stay in the same place. It's not configurable in matplotlib and, even if it were, I don't know if there is a public API for moving individual ticks. Unfortunately I think you'll have to remove the tick labels yourself after offsetting the spines.

How to add labels to c3.js scatter plot graph?

Is it possible to add labels to scatter plot points in c3.js like in this google charts example?
https://google-developers.appspot.com/chart/interactive/docs/gallery/bubblechart#javascript
c3 doesn't support this currently - https://github.com/masayuki0812/c3/issues/481. But you can easily add the functionality - just loop through the chart series and points and add the labels as necessary.
var labels = [
['AA', 'BB', 'CC', 'DD', 'EE', 'FF', 'GG', 'HH'],
['ZA', 'ZB', 'ZC', 'ZD', 'ZE', 'ZF', 'ZG', 'ZH']
];
// series
var series = chart.internal.main
.selectAll('.' + c3.chart.internal.fn.CLASS.circles)[0];
// text layers
var texts = chart.internal.main
.selectAll('.' + c3.chart.internal.fn.CLASS.chartTexts)
.selectAll('.' + c3.chart.internal.fn.CLASS.chartText)[0]
series.forEach(function (series, i) {
var points = d3.select(series).selectAll('.' + c3.chart.internal.fn.CLASS.circle)[0]
points.forEach(function (point, j) {
d3.select(texts[i])
.append('text')
.attr('text-anchor', 'middle')
.attr('dy', '0.3em')
.attr('x', d3.select(point).attr('cx'))
.attr('y', d3.select(point).attr('cy'))
.text(labels[i][j])
})
});
Fiddle - http://jsfiddle.net/6phuuans/
Currently C3.js doesnt provide us with the option to add labels to a scatter plot chart. But the following method can be used to add responsive data labels:
After the chart is rendered (in the "onrendered" property of the chart), identify the data points ( tags) and add tags with the x and y coodinates picked from the relevant circle, as the tags sibling.
Code Snippet:
onrendered: function(){
// get the parent of the the <circles> to add <text as siblings>
var g = d3.selectAll('.c3-circles');
//Get all circle tags
var circles = d3.selectAll('circle')[0];
//go to each circle and add a text label for it
for(var i = 0; i < circles.length; i++){
//fetch x-coordinate
var x = $(circles[i])[0].cx;
//fetch y-coordinate
var y = $(circles[i])[0].cy;
//create and append the text tag
g.append('text')
.attr('y', y.baseVal.value - 15) // (-15) places the tag above the circle, adjust it according to your need
.attr('x', x.baseVal.value)
.attr('text-anchor', 'middle')
.attr('class', 'c3-text c3-text-'+i)
.text(data[i].<data point key>) // the text that needs to be added can be hard coded or fetched for the original data.
//Since I am using a JSON to plot the data, I am referencing it and using the key of the value to be shown.
}
}
This will add the label, but on resize , multiple data labels will be plotted. To handle that, on the charts resize, we must remove the previous data labels (in the "onresize" property of the chart).
Code Snippet:
onresize: function () {
$('.c3-shapes.c3-circles text').remove();
}

Appending different size font in a custom label

I have created a label that displays a high score. I want to add the units ft to the end since the the score is a distance. I am using a custom font and simply adding ft to the end of the end results in FT which is to big due to the font size and font. I am wonder if i can reduce the font size and add it to the end.
This is the code i have so far:
var highscoreLabel:SKLabelNode!
highscoreLabel = SKLabelNode(fontNamed: "Komika Axis")
highscoreLabel.fontSize = 16
highscoreLabel.zPosition = 5
highscoreLabel.fontColor = UIColor.whiteColor()
self.addChild(highscoreLabel)
var highscoreShow = defaults.integerForKey("RegularHighscore")
highscoreLabel.text = "High score: \(highscoreShow)"
// High Score: \(highscoreShow) (ft in a smaller font size)"
I want to add ft in a smaller font size than the rest of the text in the label.
Attributed string will help there:
var ftString = NSMutableAttributedString(string:"ft", attributes:[NSFontAttributeName : UIFont(name: "Komika Axis", size: 10.0)])
highscoreLabel.attributedText = NSMutableAttributedString(string:"\(highscoreShow)").appendAttributedString(ftString)

Resources